gpt4 book ai didi

c++ - 委派构造函数问题——安全吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:14:28 25 4
gpt4 key购买 nike

code在一个 ctor 中调用另一个 ctor:

#include <iostream>
using namespace std;

class F {
public:
F() { cout << "ctor1\n"; }
F(int) { cout << "ctor2\n"; }
~F() { cout << "dtor\n"; }
};
class Foo {
F f;
public:
Foo() : f() { cout << "1\n"; }
Foo(int i) : f(i) { Foo(); cout << "2\n"; }
};

int main() {
Foo object(1);
return 0;
}

结果是:

ctor2
ctor1
1
dtor
2
dtor

好像这里的成员变量f被销毁了两次,可以吗?

最佳答案

这里

Foo(int i) { Foo(); cout << "2\n"; }

您没有使用委托(delegate)构造函数。您正在做的是在构造函数主体中创建 Foo 的临时实例(并立即销毁它)。

委托(delegate)构造函数的正确语法是

Foo(int i) : Foo() { cout << "2\n"; }

关于c++ - 委派构造函数问题——安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31155849/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com