【发布时间】:2016-10-14 12:07:57
【问题描述】:
我有一个简单的 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
这是标准行为(如果是,为什么会这样?)还是我犯了一些错误?我可以防止这种情况吗?
【问题讨论】:
-
添加复制构造函数和赋值运算符看看是怎么回事
-
以下所有答案中提到的副本在第一种情况下是elided。如果您使用
g++ -fno-elide-constructors编译,您将看到调用了 2 个析构函数。 -
嗯,这很有趣。谢谢!
-
这不是问题,但不要使用
std::endl,除非您需要它的额外功能。'\n'结束一行。
标签: c++ destructor method-chaining