- Code error: modify
array.clear(); on array.~vector<int>();
Explanation: operator= uses a new placement over an object that has not been destroyed, which can do anything, but you can practically expect the dynamic memory leak used by the previous array ( clear() doesnβt free memory / change capacity, it just destroys the elements and size changes).
From 9.5 / 2:
If any non-static member of the union data has a non-trivial default value, constructor (12.1), copy constructor (12.8), move constructor (12.8), copy assignment operator (12.8), move (12.8) or destructor (12.4), the corresponding member function the union must be the user or it will be implicitly deleted (8.4.3) for the association.
So, the vector constructor, destructor, etc. they never start on their own: you must invoke them explicitly whenever you want.
An example is given in 9.5 / 3:
Consider the following union:
union U { int i; float f; std::string s; };
Since std :: string (21.3) declares non-trivial versions of all special member functions, U will have an implicitly deleted default constructor, copy / move constructor, copy / move operator and destructor. To use U, some or all of these member functions must be provided by the user.
This last bit is "To use U, some or all of these member functions must be provided by the user." - it seems that it is supposed that U should coordinate its own indefinite value-semantic behavior, but in your case it means that the struct does this, so you do not need to define any of these union member functions.
2: we must call the array destructor whenever the value of the array is replaced with a boolean value. If in operator= new value of the array instead of the location is assigned the location new ed, then the old array should also have its own destructor, but using operator= will be more efficient if the existing memory is enough for all elements to be copied. In principle, you must comply with structures and demolitions. UPDATE: The sample code contains an error as per your comment below.
3: Why is a new placement required instead of doing something like "array = ms.array"?
array = ms.array calls std::vector<int>::operator= , which always assumes that the this pointer refers to an already properly constructed object. Inside this object, you can expect that there will be a pointer that will either be NULL, or refer to some internal buffer with a short string, or refer to a bunch. If your object has not been destroyed, then operator= can call the function to free memory on a dummy pointer. The new placement says "ignore the current contents of the memory that this object will occupy, and build a new object with valid members from scratch.