Why an auto_ptr can "seal" a container

Posted by icephere on Stack Overflow See other posts from Stack Overflow or by icephere
Published on 2010-06-15T19:55:46Z Indexed on 2010/06/15 20:02 UTC
Read the original article Hit count: 384

Filed under:
|
|

auto_ptr on wikipedia said that "an auto_ptr containing an STL container may be used to prevent further modification of the container.". It used the following example:

auto_ptr<vector<ContainedType> > open_vec(new vector<ContainedType>);

open_vec->push_back(5);
open_vec->push_back(3);

// Transfers control, but now the vector cannot be changed:
auto_ptr<const vector<ContainedType> > closed_vec(open_vec); 

// closed_vec->push_back(8); // Can no longer modify

If I uncomment the last line, g++ will report an error as

t05.cpp:24: error: passing ‘const std::vector<int, std::allocator<int> >’ 
as ‘this’   argument of ‘void std::vector<_Tp, _Alloc>::push_back(const _Tp&) 
[with _Tp = int, _Alloc = std::allocator<int>]’ discards qualifiers

I am curious why after transferring the ownership of this vector, it can no longer be modified?

Thanks a lot!

© Stack Overflow or respective owner

Related posts about c++

Related posts about stl