为什么 auto_ptr 可以“密封”一个容器
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
我很好奇为什么在转移该向量的所有权后,它不能再被修改?
多谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
close_vec
指针保存类型const vector
。由于类型为const
,因此您无法调用其上未定义为const
的任何方法(这意味着它们不会更改内部数据)。当然push_back
是非常量的,因为它改变了向量,所以你不能在 const 指针上调用它。它实际上与 auto_ptr 没有任何关系,您可以使用常规指针完成相同的任务:The
closed_vec
pointer holds the typeconst vector<ContainedType>
. Because the type isconst
, you can't call any methods on it that aren't also defined asconst
(which means they don't change internal data). Naturallypush_back
is non-const, as it changes the vector, so you can't call it on a const pointer. It doesn't really have anything to do withauto_ptr
, you could accomplish the same with regular pointers:您无法修改向量,因为
close_vec
是一个指向 const 的指针,因此编译器不会让您修改指针(但您仍然可以移动指针)。要允许修改向量,请将close_vec
声明为如果您已将指针声明为
另一方面,您将能够更改指针,但无法移动指针。
You can't modify the vector because
closed_vec
is a pointer-to-const, so the compiler won't let you modify the pointer (but you could still move the pointer). To allow modification of the vector, declareclosed_vec
asIf you had declared the pointer as
on the other hand, you would be able to change the pointee, but not move the pointer.