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?