C++方法链接导致析构函数被调用两次

标签 c++ destructor method-chaining

我有一个使用方法链的简单 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/

相关文章:

C++ 变量不会在范围末尾被删除

python - `weakref` 回调可以替换 `__del__` 吗?

pandas - 如何使用方法链接跨列使用 groupby 转换?

eclipse - Eclipse 可以生成方法链 setter 吗

c++ - c++使用std::enable_if有条件地将 setter/getter 添加到可变参数变体模板中

c# - UE4 波浪水 Material 和网格问题

C++ 动态数组大小定义

c++ - 将以\r\n 分隔的字符串拆分为字符串数组 [C/C++]

c++ - 用 return 语句结束析构函数是否安全?

php - 如何在新创建的对象上链接方法?