C++ 多个析构函数调用

C++ 多个析构函数调用,c++,c++11,C++,C++11,我运行了以下代码 #include <iostream> using namespace std; class Base { protected: int count=0; public: Base() { cout << "Constructor called" << endl; } ~Base() { cout << "Destructor called" << endl; } int getCou

我运行了以下代码

#include <iostream>
using namespace std;

class Base
{
protected:
    int count=0;
public:
    Base() { cout << "Constructor called" << endl; }
    ~Base() { cout << "Destructor called" << endl; }
    int getCount() {cout << "The count value is " << count << endl;}
    Base operator ++ (int) {count++;  cout << "Postfix increment called" << endl;}
    Base operator ++ () {count++;  cout << "Prefix increment called" << endl;}
};

class Derived : public Base
{
public:
    Base operator --(int)  {count--;  cout << "Postfix decrement called" << endl;}
};

int main()
{
    Derived A;
    A++;
    ++A;
    A--;
    return 0;
}

我的问题是为什么析构函数调用了这么多次?

您的运算符返回一个
基值。由于未捕获该
Base
,因此它将在表达式末尾被销毁。由于您有三个表达式,因此将得到三个析构函数调用。

您的运算符返回一个
Base
。由于未捕获该
Base
,因此它将在表达式末尾被销毁。由于有三个表达式,因此将得到三个析构函数调用。

当变量作为非引用变量传递时,编译器将使用set copy构造函数创建该变量,并在其作用域结束后将其销毁


要解决此问题,可以将变量作为引用传递。

当变量作为非引用变量传递时,编译器使用set copy构造函数创建变量,并在其作用域结束后销毁它


要解决这个问题,可以将变量作为引用传递。

首先是这些运算符

Base operator ++ (int) {count++;  cout << "Postfix increment called" << endl;}
Base operator ++ () {count++;  cout << "Prefix increment called" << endl;}
Base operator --(int)  {count--;  cout << "Postfix decrement called" << endl;}

实际上是临时对象。

首先是这些操作符

Base operator ++ (int) {count++;  cout << "Postfix increment called" << endl;}
Base operator ++ () {count++;  cout << "Prefix increment called" << endl;}
Base operator --(int)  {count--;  cout << "Postfix decrement called" << endl;}

实际上是临时对象。

从概念上讲,每个操作符都会向调用者返回一个类型为
Base
的临时对象。该临时对象在每次操作员调用后都会被销毁。这种破坏正是你在实验中观察到的


但是,您忘记在运算符定义中包含
return
语句。因为您的代码具有未定义的行为。

从概念上讲,每个操作符都会向调用者返回一个类型为
Base
的临时对象。该临时对象在每次操作员调用后都会被销毁。这种破坏正是你在实验中观察到的


但是,您忘记在运算符定义中包含
return
语句。因为您的代码具有未定义的行为。

您不监视复制构造(和移动语义)-换句话说,测试有缺陷运算符中的返回在哪里?是否编译(没有警告)是的,它编译没有警告在g++编译器。@萨西什:丢失的回报触发未定义的行为在C++中。无论如何,您看到的析构函数调用只是销毁了从您的成员函数返回的临时
Base
对象。@Sathish如果您将警告视为错误,则它不应编译:您不监视复制构造(和移动语义)-换句话说,测试有缺陷运算符中的返回在哪里?是否编译(没有警告)是的,它编译没有警告在g++编译器。@萨西什:丢失的回报触发未定义的行为在C++中。无论如何,您看到的析构函数调用只是销毁了从成员函数返回的临时
Base
对象。@Sathish如果将警告视为错误,则不应编译:
Base operator ++ (int) 
{
    count++;  
    cout << "Postfix increment called" << endl;
    return *this;
}
A++;
++A;
A--;