auto_ptr on wikipedia表示“一个包含STL容器的auto_ptr可能被用来阻止对容器的进一步修改”。它使用了下面的例子:为什么一个auto_ptr可以“密封”一个容器
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
如果我去掉最后一行,G ++将报告作为
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
我很好奇的错误,为什么转移这一载体的所有权后,就再也不能改性?
非常感谢!
非常感谢! :)我忽略了closed_vec中的“const”。 – icephere 2010-06-15 20:02:38
它_does_与auto_ptr有关。使用常规指针,旧的非const指针仍然可以用来修改容器。所有权转让后,非常量auto_ptr将为NULL。 – MSalters 2010-06-16 09:51:01