gpt4 book ai didi

c++ - 为什么 boost::make_shared 使用复制语义

转载 作者:行者123 更新时间:2023-11-28 02:05:01 25 4
gpt4 key购买 nike

我有一个小程序,我无法理解它的工作原理。

class A {
public:
A() {
cout<<"Costructor called"<<endl;
}

~A() {
cout<<"Destructor called"<<endl;
}
};

A foo() {
return A();
}


int main() {
A obj = foo();
cout<<"A initialized "<<endl;
boost::shared_ptr<A> ptr1 = boost::make_shared<A>(foo());
cout<<"ptr1 initialized "<<endl;
return 0;
}

输出是:-

./a.out
Costructor called
A initialized
Costructor called
Destructor called
ptr1 initialized
Destructor called
Destructor called

为什么 A 在创建 ptr 时被初始化和销毁​​,而在创建 obj 时却没有?

最佳答案

让我们通过添加一个复制构造函数并在每个特殊成员中打印 this 让您的类更嘈杂

class A {
public:
A() {
cout<<"Constructor called "<< this << endl;
}

A(A const&) {
cout<<"Copy Constructor called "<< this << endl;
}

~A() {
cout<<"Destructor called "<< this << endl;
}
};

Live demo

这会产生输出

Constructor called 0x7fff0ed4883e   // obj is constructed
A initialized
Constructor called 0x7fff0ed4883f // return value of foo() is constructed in make_shared call
Copy Constructor called 0x1430c39 // shared_ptr copy constructs A from return value of foo()
Destructor called 0x7fff0ed4883f // return value of foo() is destroyed
ptr1 initialized
Destructor called 0x1430c39 // shared_ptr deletes the A it owns
Destructor called 0x7fff0ed4883e // obj is destroyed

关于c++ - 为什么 boost::make_shared 使用复制语义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37869303/

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