由于某些原因,我试图跟踪该程序 流程结束,退出代码为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);
}
答案 0 :(得分:4)
您的程序表现出未定义的行为,这是通过到达非void函数的闭合括号(此处为operator=
)而没有遇到return
语句。
答案 1 :(得分:3)
对我来说(使用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
也许您应该尝试解决警告。