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
is semantically equivalent to
Hence it
TestDataElement1in that spot,test2.testDataElement1.So you’re only outputting the value of a copy of
test1twice.By the way, you’ll never be able to create a
shared_ptrto memory on the stack unless you specify a custom deleter.