-1

I have this question because I am reading the section for auto_ptr. It says auto_ptr cannot be saved in a vector because of its destructive copy and assignment. I can understand it somehow and one example I can think of is something like auto_ptr ap = vec[0] will surprise me. But what if I use it cautiously and do not do this, can I store auto_ptr in a vector? Is there any deeper reason why I cannot store? Maybe the implementation of vector internally needs this assumption that elements need to be copy constructable?

Thanks.

Sean
  • 2,649
  • 3
  • 21
  • 27
  • 3
    `auto_ptr` is deprecated and very hard to use correctly. Try switching to `unique_ptr`, it will make things much easier for you. – Alan Stokes Nov 14 '15 at 08:51

2 Answers2

0

When a vector is resized, its elements are copied to a new backing array, this is where the copy constructor is used. If you have a sufficiently new compiler, look into using std::unique_ptr instead.

pmdj
  • 22,018
  • 3
  • 52
  • 103
0

Because vector has to store an already constructed object inside its storage. So, it has to copy the object into its own storage.

Also vector to assure scope-safety, it has to copy/move the object passed.

See the documentation of push_back

std::vector::push_back
void push_back( const T& value );   (1)
void push_back( T&& value );    (2)     (since C++11)

Appends the given element value to the end of the container.

1) The new element is initialized as a copy of value.

2) value is moved into the new element.

Parameters

value - the value of the element to append

Type requirements

  • T must meet the requirements of CopyInsertable in order to use overload

  • T must meet the requirements of MoveInsertable in order to use overload

And CopyInsertable id defined as

Specifies that an instance of the type can be copy-constructed in-place, in uninitialized storage.

g-217
  • 2,069
  • 18
  • 33