没有调用析构函数?

Destructors not called?

我正在尝试跟踪此程序,但由于某种原因它显示 进程以退出代码 4 结束。 并在不调用析构函数的情况下结束?可能是什么原因?

#include <iostream>
using namespace std;

class A {
public:
    A() { cout << "A ctor" << endl; }
    A(const A& a) { cout << "A copy ctor" << endl; }
    virtual ~A() { cout << "A dtor" << endl; }
    virtual void foo() { cout << "A foo()" << endl; }
    virtual A& operator=(const A& rhs) { cout << "A op=" << endl; }
};

class B : public A {
public:
    B() { cout << "B ctor" << endl; }
    virtual ~B() { cout << "B dtor" << endl; }
    virtual void foo() { cout << "B foo()" << endl; }
protected:
    A mInstanceOfA; // don't forget about me!
};
A foo(A& input)
{
    input.foo();
    return input;
}
int main()
{
    B myB;

    B myOtherB;
    A myA;
    myOtherB = myB;
    myA = foo(myOtherB);
}

您的程序表现出未定义的行为,即到达 non-void 函数的右大括号(此处为 operator=)而没有遇到 return 语句。

对我来说(使用 gcc 8.3.0)效果很好。但我收到警告:

test.cpp: In member function ‘virtual A& A::operator=(const A&)’:
test.cpp:10:63: warning: no return statement in function returning non-void [-Wreturn-type]
 virtual A& operator=(const A& rhs) { cout << "A op=" << endl; }

然后打印出来:

A ctor
A ctor
B ctor
A ctor
A ctor
B ctor
A ctor
A op=
A op=
B foo()
A copy ctor
A op=
A dtor
A dtor
B dtor
A dtor
A dtor
B dtor
A dtor
A dtor

也许你应该尝试解决这个警告。