Search code examples
c++c++11constructorinitializationunique-ptr

unique_ptr in member initialization list


EDIT: I understand unique_ptr is non-copyable and can be only moved. i do not understand what happens with the initialization list.

Why unique_ptr in member initialization list can work as in the code snipt?

#include <memory>

class MyObject
{
public:
    MyObject() : ptr(new int) // this works.
    MyObject() : ptr(std::unique_ptr<int>(new int)) 
    // i found this in many examples. but why this also work? 
    // i think this is using copy constructor as the bottom.        
    {
    }

    MyObject(MyObject&& other) : ptr(std::move(other.ptr))
    {
    }

    MyObject& operator=(MyObject&& other)
    {
        ptr = std::move(other.ptr);
        return *this;
    }

private:
    std::unique_ptr<int> ptr;
};

int main() {
    MyObject o;
    std::unique_ptr<int> ptr (new int);
    // compile error, of course, since copy constructor is not allowed. 
    // but what is happening with member initialization list in above?
    std::unique_ptr<int> ptr2(ptr); 
}

Solution

  • In your example, std::unique_ptr<int>(new int) is an rvalue, so the move-constructor of ptr is used.

    The second time (in main), std::unique_ptr<int> ptr2(ptr) doesn't work because ptr is an lvalue, and cannot be moved directly (you can use std::move).