【发布时间】:2021-05-25 16:44:21
【问题描述】:
我编写了这段代码来学习在我自己的类中创建 shared_ptr 对象。 为什么 A 对象 shared_ptr 在 A 的 print (obj->print() inside B's print) 被调用之前就被销毁了?
#include <iostream>
#include <memory>
using namespace std;
class A {
private: string str;
public:
A(string s){
str = s;
cout<<"class A: "<< str << endl;}
~A() { cout << "destroying A: " << str << endl;}
void print() { cout << "A print called" << endl;}
};
class B {
private: shared_ptr<A> obj;
public:
B() { cout << "default construct called" << endl;}
B(string s) {
cout << "shared_ptr creation" <<endl;
shared_ptr<A> obj = make_shared<A>(s);
cout << "shared_ptr creation done" <<endl;
}
~B() { cout<<"destroying B" << endl;}
void print() { obj->print();cout << "B print called" << endl;}
};
void func( B i) { i.print();}
int main()
{
{
B b("hello world");
func(b);
}
cout << "in main" << endl;
return 0;
}
输出:
shared_ptr 创建
A类:你好世界
shared_ptr 创建完成
毁灭 A:你好世界
一个名为
的印刷品
B 打印调用
破坏B
破坏B
在主要
【问题讨论】:
标签: c++