c++11unique-ptrplacement-newnoncopyable

Placement new for non-copyable objects


I'm trying to simulate a vector of unique pointers just to learn how placement new works with objects that cannot be copied.

class Person
{
    string name;
    const int born;
public:
    Person (string N, int B) : name(N), born(B) {}
};

int main()
{
    using T = unique_ptr <Person>;
    int capacity = 4, size = 0;
    T* royals = (T*) ::operator new (sizeof(T) * capacity);

    for (const T& item: {
        make_unique <Person> ("Elizabeth", 1926),
        make_unique <Person> ("Philip", 1921) })
    {
        new (royals + size) T(item);
        ++size;
    }
    ::operator delete (royals);
}

The line new (royals + size) T(item) is a compile error because unique pointers cannot be copied.

Instead of copying, we must move unique pointers. Unfortunately in this case, they cannot be moved because they live inside an initializer list.

Is there a workaround to this problem?


Solution

  • Initialize the unique pointers in an array instead of initializer list. Objects in an array can be moved out, unlike objects in an initializer list.

    int main()
    {
        using T = unique_ptr <Person>;
        int capacity = 4, size = 0;
        T* royals = (T*) ::operator new (sizeof(T) * capacity);
    
        T init[] = {
            make_unique <Person> ("Elizabeth", 1926),
            make_unique <Person> ("Philip", 1921)
        };
        for (T& item: init)
        {
            new (royals + size) T(move(item));
            ++size;
        }
        ::operator delete (royals);
    }