Search code examples
c++classsmart-pointers

Nested class constructed in a member function with smart pointers in c++


I have the following simple code

class Hybrid{
   std::unique_ptr<Bcf> bndfac; 


   void constructbndFace( const int &nn){ 
      bndfac( new Bcf(nn) ); // Does not work (A)
      //std::unique_ptr<Bcf> bndfac( new Bcf(nn) ); // WORKS (B)
   }
 }

class Bcf{
   Bcf(const int nn_) : nn(nn_){}
 private:
    int nn;
 }

When I try to invoke Hybrid::constructbndFace I don't understand why the compiler complains that std::unique_ptr< Bcf >' does not provide a call operator. If I use the commented line (B) the compiler no longer complains.

My question is if I use the (B) line, would the object instantiated be accessed through my declaration in the Hybrid class, or am I doing something terribly wrong Hybrid->bndFace


Solution

  • In you line B you create a temporary object with the name that shadows member name. Then it is destroyed at the next line with closing curved bracket.

    If you want to construct bndfac object, you should replace your line B with this:

    bndfac = std::make_unique<Bcf>(nn);