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