以下是实际问题的简化版本。Base::operator=(int)
代码似乎生成了一个临时Derived
对象并复制它,而不是 call 。为什么不使用基本赋值运算符,因为函数签名似乎完美匹配?这个简化的示例没有显示任何不良影响,但原始代码在析构函数中有一个副作用,会导致各种破坏。
#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()