c++ - 如何在 C++ 中创建 scoped_ptr 映射

标签 c++ dictionary scoped-ptr

我有以下代码,第 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_ptrnon-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/

相关文章:

C++ 3d游戏开发

c++ - 无法在屏幕上打印 nullptr 的值

javascript - 在map.arc()中循环Json对象

java - 通用编程 : error when trying to put values in an EnumMap

c++ - 将对象函数转换为函数指针

c++ - Qt UIThreadWidget

c# - 尝试修改字典时出现异常

c++ - 应该使用哪个 header 来使用 scoped_ptr

c++ - scoped_ptr 中的对象分配速度非常快?