wikipedia 上的 auto_ptr 说“包含 STL 容器的 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
我很好奇为什么转移了这个vector的所有权后,就不能再修改了?
非常感谢!