如何在 C++ 中创建 scoped_ptr 的地图

How to create map of scoped_ptr in c++

我有以下代码,第 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_ptrs 到容器中,因为在这种情况下不执行复制:

std::list<boost::scoped_ptr<MyClass>> list;
list.emplace_back(new MyClass());

boost::scoped_ptr不可复制,但您仍然可以交换它。​​

这是一个技巧:

// Example program
#include <iostream>
#include <string>
#include <map>
#include <boost/scoped_ptr.hpp>

int main()
{
  std::map<int, boost::scoped_ptr<int>> myMap;

  int * test = new int();
  *test = 589;

  boost::scoped_ptr<int> myScoped(test);

  boost::swap(myMap[1], myScoped);

  std::cout << *myMap[1];

}

给出:

589

参见 C++ Shell : http://cpp.sh/3zm3

但是,我劝你不要这样做。