我有一个使用方法链的简单 C++ 程序,我注意到析构函数仅在链调用中使用时被调用两次。仅当链调用也包含构造函数时才会发生这种情况。如果单独调用,析构函数只调用一次。
代码如下:
class Foo {
public:
Foo() { cout << "-- constructor " << this << endl; }
~Foo () { cout << "-- destructor " << this << endl; };
Foo& bar() {
cout << "---- bar call " << this << endl;
return *this;
}
};
int main() {
cout << "starting test 1" << endl;
{
Foo f = Foo();
}
cout << "ending test 1" << endl << endl;
cout << "starting test 2" << endl;
{
Foo f = Foo().bar();
}
cout << "ending test 2" << endl;
return 0;
}
此应用程序的结果如下:
starting test 1
-- constructor 0x7ffd008e005f
-- destructor 0x7ffd008e005f
ending test 1
starting test 2
-- constructor 0x7ffd008e005f
---- bar call 0x7ffd008e005f
-- destructor 0x7ffd008e005f
-- destructor 0x7ffd008e005f
ending test 2
这是标准行为(如果是,那是为什么?)还是我犯了一些错误?我可以阻止这种情况吗?
最佳答案
Foo f = Foo().bar();
还调用了 Foo
的复制构造函数,这是当前编译器的构造函数生成,因此不会向控制台输出任何内容。 这就是为什么您调用的析构函数多于构造函数的原因。
您可以编写 const Foo& f = Foo().bar();
来避免复制。使用 const
还可以延长匿名临时对象的生命周期,这很好。
关于C++方法链接导致析构函数被调用两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40042813/