0

I am having a problem initializing a boost::shared_ptr when it is a member variable of a class. I saw this previous question:

How to initialize a shared_ptr that is a member of a class?

However I still have a compiler error. Quick example code:

class A
{
    public:
      A();
};

class B
{
    public:
       B();
    private:
        boost::shared_ptr<A> mA;

        foo() {

           // the line below generates a compiler error
           mA(new A());       // ERROR

           // below will work....
           boost::shared_ptr<A> tmp(new A());    //OK
           mA = tmp;

        }
 };

The compiler complains with: error: no match for call to "(boost::shared_ptr<A>) (A*)"

However creating a tmp shared_ptr and then assigning it to mA compiles fine. I am cross-compiling on an Ubuntu 14.04 machine for an Intel Edison.

What am I missing?

0andriy
  • 4,183
  • 1
  • 24
  • 37
vagrant4ever
  • 35
  • 1
  • 6
  • 2
    Use the constructor initializer list - `foo() : mA(new A()) {...}` or `foo() : mA(boost::make_shared()) {...}` – Praetorian Apr 10 '15 at 21:37
  • 1
    This has **nothing** to do with `shared_ptr`, if `mA` was an `int` then you would have the same problem trying to do `mA(0)` in the constructor body. Members are already initialized by the time the constructor body starts, so you either need to initialize them earlier (in the mem-initializer list) or assign to them in the body. Get a good book on C++. – Jonathan Wakely Apr 12 '15 at 14:32
  • I disagree. If mA was an int I would have used the mem-initializer list, or set it in the constructor body, ma = 2 or whatever. It was my ignorance of initializing a shared_ptr, that I posted the question. – vagrant4ever Apr 13 '15 at 14:42

1 Answers1

2

You are looking for mA.reset(new A());

Also shared pointer is part of the standard now, so you should use std::shared_ptr

dwcanillas
  • 3,562
  • 2
  • 24
  • 33