简体   繁体   中英

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM