Correct usage of unique_ptr in class member

unique_ptr class member initialization
make_unique vs unique_ptr
unique_ptr implementation
unique_ptr c
when to use unique_ptr
unique_ptr assignment
unique_ptr polymorphism
unique_ptr::get

I am trying to really move from c++98 to c++11 and newer. I have wrapped my head over most of the new stuff but I am still not sure about the correct usage of unique_ptr.

Consider the example below, where class A has a unique_ptr member (I would have used raw pointer before!). This member variable should be assigned, when user needs, by calling a function somewhere else (not part of the class). Is this the correct usage? If not, what is the best alternative?

class A {
private:
   unique_ptr<MyType> mt;
public:
   void initStuff() {
      mt.reset(std::move(StaticFuncSomewhereElese::generateMyType()));
   } 
};

MyType* StaticFuncSomewhereElese::generateMyType() {
    MyType* temp = new MyType(...);
    //do stuff to temp (read file or something...)
    return temp;
}

Your code works fine (although the redundant* move can be omitted) but it would be better to construct the unique_ptr as early as possible:

class A {
private:
   std::unique_ptr<MyType> mt;
public:
   void initStuff() {
      mt = StaticFuncSomewhereElese::generateMyType();
   } 
};

std::unique_ptr<MyType> StaticFuncSomewhereElese::generateMyType() {
    auto temp = std::make_unique<MyType>(…);
    // `make_unique` is C++14 (although trivially implementable in C++11).
    // Here's an alternative without `make_unique`:
    // std::unique_ptr<MyType> temp(new MyType(…));

    //do stuff to temp (read file or something...)
    return temp;
}

This way it is clear that the return value of generateMyType must be deleted by the caller, and there's less possibility for memory leaks (e.g. if generateMyType returns early).

* The move is redundant because:

  1. Raw pointers can't be moved.
  2. The result of the generateMyType() expression is already an rvalue anyways.

Correct usage of unique_ptr in class member, Updated 23rd February 2013: Fixed typos in the code, incorrect use of const, clarified the use of the terms "initialization" and "assignment" to be  You can, of course, use std::unique_ptr as a composition member of your class. This way, you don’t have to worry about ensuring your class destructor deletes the dynamic memory, as the std::unique_ptr will be automatically destroyed when the class object is destroyed.

Is this the correct usage?

Besides std::move being redundant, yes this is correct. It is redundant because a) Bare pointers are copied, whether they are lvalues or rvalues and b) The function doesn't return a reference, so the return value is already an rvalue so there is no need to convert.

But there is room for improvement. In particular, I recommend to return a unique pointer from the factory function:

std::unique_ptr<MyType> StaticFuncSomewhereElese::generateMyType()

This prevents temp from leaking if the initialization throws an exception, and makes it much harder for the user of the factory to accidentally leak the returned pointer.

C++11: Using std::unique_ptr as a class member: initialization, move , Using std::unique_ptr as a class member (C++11). Posted on In fact, if you ever intend to use smart pointers to manage a class, you should add a typedef there. Seems like shared pointers is one size fits all right? I would  C++11: Using std::unique_ptr as a class member: initialization, move semantics and custom deleters | Katy's Code. Updated 23rd February 2013: Fixed typos in the code, incorrect use of const, clarified the use of the terms “initialization” and “assignment” to be semantically correct, corrected/clarified references to “constructor” and “assignment operator”, added an explanation of the default copy assignment operator and unique_ptr’s private copy constructor and copy

Why not make it a generic template factory?

In header.

template <typename T>
std::unique_ptr<T> generateMyType();

classss A {
private:
   std::unique_ptr<MyType> mt;
   std::unique_ptr<MyOtherType> mot;
public:
   void initStuff() {
      mt = generateMyType<MyType>();
      mot = generateMyType<MyOtherType>();
   } 
};

And in the source file

template <typename T>
std::unique_ptr<T> generateMyType()
{
  auto temp = std::make_unique<T>();
  return temp;
}

Using std::unique_ptr as a class member (C++11), Making unique_ptr class members work with Forward Declarations correctly for all your classes, and cleaner and simpler just to use  unique_ptris defined in the <memory>header in the C++ Standard Library. It is exactly as efficient as a raw pointer and can be used in C++ Standard Library containers. The addition of unique_ptrinstances to C++ Standard Library containers is efficient because the move constructor of the unique_ptreliminates the need for a copy operation. Example 1

How to: Create and use unique_ptr instances, This member variable should be assigned, when user needs, by calling a function somewhere else (not part of the class). Is this the correct usage? If not, what is  std::unique_ptr is a smart pointer that owns and manages another object through a pointer and disposes of that object when the unique_ptr goes out of scope. The object is disposed of, using the associated deleter when either of the following happens: the managing unique_ptr object is destroyed. the managing unique_ptr object is assigned another pointer via operator= or reset () .

Lesson #4: Smart Pointers, std::unique_ptr is commonly used to manage the lifetime of objects, including: providing exception safety to classes and functions that handle  It is all about ownership expression. If only one person will ever own the pointer then a unique_ptr is more appropriate. If ownership is shard then a shared_ptr is appropriate. – NathanOliver May 9 '17 at 17:50

Correct usage of unique_ptr in class member - c++ - android, [C++] Some issues with using a unique_ptr as a class member variable I need to use the appropriate SDL_DestroyX function to free the variable's memory, nothing, or trying to find a bug fix / new feature that I am actually capable of doing. I'm having trouble understanding the usage of smart pointers as class members in C++11. I have read a lot about smart pointers and I think I do understand how unique_ptr and shared_ptr/weak_ptr work in general. What I don't understand is the real usage. It seems like everybody recommends using unique_ptr as the way to go almost all the time

Comments
  • You don't need the std::move there, raw pointers can't be moved.
  • @tuple_cat But this compiles and runs flawlessly
  • @SaeidYazdani You don't need it though. Rather use std::make_unique().
  • @πάνταῥεῖ Then what would be the return type of the generator function?
  • @SaeidYazdani std::unique_ptr<MyType>.
  • Note that the question is tagged C++11, so it might be worth mentioning that std::make_unique wasn't introduced until C++14.