下面是一个实际的问题的一个简化版本。 而不是调用Base::operator=(int)
将码出现生成临时Derived
对象和副本来代替。 为什么不基地赋值运算符习惯,因为函数签名似乎完美地匹配? 该简化示例中不显示任何不良影响,但原码具有在导致各种严重破坏的析构函数的副作用。
#include <iostream>
using namespace std;
class Base
{
public:
Base()
{
cout << "Base()\n";
}
Base(int)
{
cout << "Base(int)\n";
}
~Base()
{
cout << "~Base()\n";
}
Base& operator=(int)
{
cout << "Base::operator=(int)\n";
return *this;
}
};
class Derived : public Base
{
public:
Derived()
{
cout << "Derived()\n";
}
explicit Derived(int n) : Base(n)
{
cout << "Derived(int)\n";
}
~Derived()
{
cout << "~Derived()\n";
}
};
class Holder
{
public:
Holder(int n)
{
member = n;
}
Derived member;
};
int main(int argc, char* argv[])
{
cout << "Start\n";
Holder obj(1);
cout << "Finish\n";
return 0;
}
输出是:
Start
Base()
Derived()
Base(int)
Derived(int)
~Derived()
~Base()
Finish
~Derived()
~Base()
http://ideone.com/TAR2S