0

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

Constantinos Glynos
  • 2,952
  • 2
  • 14
  • 32

1 Answers1

0

Fixed when changing the constructor from:

Foo() : m_foo( std::make_shared<Bar>(Bar(23)) )   // Ex.1

to

Foo() : m_foo( std::make_shared<Bar>(23) )   // Ex.1

There's something about calling the constructor inside the make_shared arguments. I still don't know why so if anyone knows more about this please do answer the question in detail.

Constantinos Glynos
  • 2,952
  • 2
  • 14
  • 32