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.
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
TestDataElement1 in that spot,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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With