我有以下代码,第 2 行在编译期间给我一个错误。是否可以创建作用域指针的映射,或者我是否必须改用共享指针?
map<int, scoped_ptr> mp;
mp[1] = scoped_ptr(new obj());
错误:
boost::scoped_ptr<T>& boost::scoped_ptr<T>::operator=(const boost::scoped_ptr<T>&) [with T = ]’ is private
最佳答案
你不能,boost::scoped_ptr
是 non-copyable通过设计(强调我的):
The scoped_ptr template is a simple solution for simple needs. It supplies a basic "resource acquisition is initialization" facility, without shared-ownership or transfer-of-ownership semantics. Both its name and enforcement of semantics (by being noncopyable) signal its intent to retain ownership solely within the current scope.
<...>
scoped_ptr cannot be used in C++ Standard Library containers. Use shared_ptr if you need a smart pointer that can.
但是,您可以将 emplace shared_ptr
放入容器中,因为在这种情况下不会执行任何复制:
std::list<boost::scoped_ptr<MyClass>> list;
list.emplace_back(new MyClass());
关于c++ - 如何在 C++ 中创建 scoped_ptr 映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33608094/