I wasn't sure about the title, so apologies in advance if it's not very clear.
The example below illustrates my problem.
When I use new to initialize the shared_ptr from the Member Initialization List then when I assign a value to the &ref_bar everything seems to work fine. However, when I try the same thing with make_shared, which is the preferred way, it doesn't work.
Can you please explain what happens under the hood for this to occur?
Please ignore the "bad" coding in the following example. I've created this to illustrate my problem. I'm interested in what matters the shared_ptr.
#include <iostream>
#include <memory>
class Bar
{
int m_bar;
public:
int &ref_bar;
Bar(int bar_) : m_bar(bar_),ref_bar(m_bar)
{;}
void print()
{
std::cout<< "m_bar = "<<m_bar<<std::endl;
}
};
struct Foo
{
std::shared_ptr<Bar> m_foo;
Foo() : m_foo( std::make_shared<Bar>(Bar(23)) ) // Ex.1
//Foo() : m_foo( new Bar(23) ) // Ex.2
{
m_foo->print();
m_foo->ref_bar = 12;
m_foo->print();
}
};
int main()
{
Foo f;
}
The results are:
Ex.1 >> 23,23 Wrong.
Ex.2 >> 23,12 Ok.
Here's a link to ideone: http://ideone.com/xluYQ9