Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Boost make_shared creating a copy

Tags:

shared-ptr

I have this code:

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;

Which produce this:

TEST1: 100

TEST2: 100

But I can't understand why it doesn't produce 100, 200, since the test2 merely has a pointer to test1.

like image 865
Rune Avatar asked Feb 03 '26 13:02

Rune


1 Answers

The template function boost::make_shared behaves differently to what you expect. The line

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

is semantically equivalent to

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

Hence it

  1. allocates memory,
  2. calls the copy constructor of TestDataElement1 in that spot,
  3. creates a shared_ptr to that piece of memory
  4. and assigns it to test2.testDataElement1.

So you're only outputting the value of a copy of test1 twice.

By the way, you'll never be able to create a shared_ptr to memory on the stack unless you specify a custom deleter.

like image 70
Ralph Tandetzky Avatar answered Feb 08 '26 23:02

Ralph Tandetzky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!