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

标签 c++ boost

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

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/

相关文章:

c++ - 尝试使用外部库时 undefined reference

c++ - std::function typedef 中的参数名称

c++ - 使用带有 adjacency_list 的通用类型

c++ - 为什么 std::sub_match<T> 公开继承自 std::pair<T, T>?

javascript - 寻找将非转义字符串转换为转义字符串的工具

c++ - std::filesystem::directory_iterator 链接器问题 (C++17)

c++ - 如何忽略 getopt_long 中的无效选项

c++ - 为什么我不能通过管道从两个 execl 调用输出?

c++ - 如何序列化 boost::accumulators::accumulator_set<>?

visual-c++ - 如何使用Visual Studio 2010在Windows上编译G++