【问题标题】:why is destructor called earlier?为什么提前调用析构函数?
【发布时间】: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++


    【解决方案1】:

    在B::B(string) 中,shared_ptr&lt;A&gt; obj = make_shared&lt;A&gt;(s); 正在构造一个本地对象,该对象在构造函数结束时立即被销毁;它与数据成员obj 无关,它指向任何结果。

    我想你想要:

    B(string s) {
        cout << "shared_ptr creation" <<endl;
        obj = make_shared<A>(s); // assignment to the data member obj
        cout << "shared_ptr creation done" <<endl;
    }
    

    或者在成员初始化器列表中初始化它。

    B(string s) : obj(make_shared<A>(s)) { // initialize the data member obj
        cout << "shared_ptr creation done" <<endl;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-04
      • 2014-03-05
      • 2018-05-24
      • 2015-08-21
      • 1970-01-01
      • 2021-04-01
      • 2012-02-01
      相关资源
      最近更新 更多