shared-ptr - C++ Boost make_shared 创建一个副本

标签 shared-ptr

我有这个代码:

struct TestDataElement1
{
    unsigned int something;
};

struct TestDataElement2
{
    boost::shared_ptr<TestDataElement1> testDataElement1;
};

TestDataElement1 test1;
test1.something = 100;

TestDataElement2 test2;
test2.testDataElement1 = boost::make_shared<TestDataElement1>(test1);
cout << "TEST1: " << test2.testDataElement1 -> something << endl;
test1.something = 200;
cout << "TEST2: " << test2.testDataElement1 -> something << endl;

产生这个:

测试 1:100

测试 2:100

但我不明白为什么它不产生 100、200,因为 test2 只有一个指向 test1 的指针。

最佳答案

模板函数 boost::make_shared 的行为与您预期的不同。线路

test2.testDataElement1 = boost::make_shared<TestDataElement1>(test1);

在语义上等同于

test2.testDataElement1 = 
    boost::shared_ptr<TestDataElement1>( 
        new TestDataElement1(test1) );

因此

  1. 分配内存,
  2. 在该位置调用 TestDataElement1 的复制构造函数,
  3. 为那 block 内存创建一个 shared_ptr
  4. 并将其分配给 test2.testDataElement1

所以你只输出 test1 副本的值两次。

顺便说一句,除非指定自定义删除器,否则您将永远无法为堆栈上的内存创建 shared_ptr

关于shared-ptr - C++ Boost make_shared 创建一个副本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11848791/

相关文章:

c++ - shared_ptr 在 if 条件下如何工作

c++ - boost shared_ptr use_count 函数

c++ - 具有std::function的std::shared_ptr作为自定义删除器和分配器

c++ - 错误 : no matching member function for call to 'reset' (shared pointers)

c++ - 如何查看gdb内部智能指针的内部数据?

c++ - shared_ptr 模板参数无效

c++ - GCC 原子 shared_ptr 实现

c++ - `shared_ptr` 是如何实现协变的?

c++ - 基于模板类型重构c++模板类

c++ - 将 shared_ptr 的嵌套智能指针重置为 shared_ptr(或 unique_ptr),看似矛盾