It is not valid to have an object that contains an auto_ptr in a standard container. You run into undefined behavior. Two common problems:
- std::vector<>::resize copies its argument into each created element. The first copy will "succeed" (see below why not), but each further copy will be empty, because the element copied is also empty!
- If something during reallocation throws, you can happen to have some elements copied (to a new buffer) - but the copy being thrown away - and other elements not, because
push_back
must not have any effects if an exception is being thrown. Thus some of your elements are now empty.
As this is all about undefined behavior it does not really matter. But even if we try to come up with this behavior based on what we think is valid, we would fail anyway. All the member functions like push_back
, resize
and so on have a const reference that takes an object of type T. Thus, a reference of type T const&
is tried to copied into elements of the vector. But the implicitly created copy constructor/copy assignment operator looks like T(T&)
- that is, it requires a non-const object to be copied from! Good implementations of the Standard library check that, and fail to compile if necessary.
Until the next C++ version, you have to live with this. The next one will support element types that are merely movable. That is, a moved object does not need to be equal to the object moved to. That will allow putting streams, transfer-of-ownership pointers and threads into containers.
See what the Standard says for this (17.4.3.6
):
In certain cases (replacement functions, handler functions, operations on types used to instantiate standard library template components), the C++ Standard Library depends on components supplied by a C++ program. If these components do not meet their requirements, the Standard places no requirements on the implementation.
In particular, the effects are undefined in the following cases:
- for types used as template arguments when instantiating a template component, if the operations on the type do not implement the semantics of the applicable Requirements subclause (20.1.5, 23.1, 24.1, 26.1).