Search code examples
c++c++14new-operatorunique-ptr

Cannot initialize a pointer using std::unique_ptr


I have an object inside my class and I have declared the object without any initialization:

std::unique_ptr<tf::TransformBroadcaster> tfb_;

Then, during the construction, I have decided to initialize my tfb_:

tfb_ = std::make_unique<tf::TransformBroadcaster>(new tf::TransformBroadcaster());

I am getting an error:

error: no matching function for call to ‘tf::TransformBroadcaster::TransformBroadcaster(tf::TransformBroadcaster*)’
     { return unique_ptr<_Tp>(new _Tp(std::forward<_Args>(__args)...)); }

From my understanding, it looks like I am trying to pass an argument even though I am not (or may be?). The header file of tf::TransformBroadcaster is nothing special (just a snippet):

class TransformBroadcaster{
public:
  /** \brief Constructor (needs a ros::Node reference) */
  TransformBroadcaster();

I have tried to use a raw pointer in my header file:

tf::TransformBroadcaster* tfb_;

and in my constructor:

tfb_ = new TransformBroadcaster()

and it worked. Any idea why?


Solution

  • As there is no constructor of TransformBroadcaster that takes a TransformBroadcaster* as input, you cannot call std::make_unique<TransformBroadcaster>() with such an argument.

    In short, this line:

    tfb_ = std::make_unique<tf::TransformBroadcaster>(new tf::TransformBroadcaster());
    

    should be this:

    tfb_ = std::make_unique<tf::TransformBroadcaster>();