-1

I have a class as:

class LargeObject
{
  public:
    LargeObject();
    void DoSomething();
  private:
    std::unique_ptr<Thing> pThing;
};

Then when I want to create the pointer in the constructor

LargeObject()
{
  pThing(new Thing()); //This does not work.
}

I want to use the member variable throughout the code. How to do that?

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
user1876942
  • 1,411
  • 2
  • 20
  • 32
  • How would you initialize `pThing` if it was, say, an `int`? Try that first. When you succeed, try the `unique_ptr`. – juanchopanza Sep 10 '14 at 14:47
  • Although the linked duplicate question concerns `shared_ptr`s, `unique_ptr` can be initialized from a pointer to `Thing` the same way using constructor initialization lists. Other member variables can also be initialized in initialization lists, see [here](http://stackoverflow.com/questions/14689227/initializer-list-vs-initialization-method) and [here](http://stackoverflow.com/questions/1242830/constructor-initialization-list-evaluation-order). – In silico Sep 10 '14 at 14:52
  • OK, that seems the way to go. I will try it out. Tnx – user1876942 Sep 10 '14 at 14:54

1 Answers1

1

I think initialization should be in constructor's initialization list, that's the place where constructors should be invoked from another constructor:

LargeObject()
:pThing(new Thing){}
GingerPlusPlus
  • 5,336
  • 1
  • 29
  • 52
  • It can be, here and elsewhere it says use "new" http://www.umich.edu/~eecs381/handouts/C++11_smart_ptrs.pdf like a regular pointer. – user1876942 Sep 10 '14 at 14:51