Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/151.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何在c+中创建作用域的ptr映射+;_C++_Dictionary_Scoped Ptr - Fatal编程技术网

C++ 如何在c+中创建作用域的ptr映射+;

C++ 如何在c+中创建作用域的ptr映射+;,c++,dictionary,scoped-ptr,C++,Dictionary,Scoped Ptr,我有下面的代码,第2行在编译过程中给了我一个错误。是否可以创建作用域指针的映射,还是必须使用共享指针 map<int, scoped_ptr> mp; mp[1] = scoped_ptr(new obj()); map-mp; mp[1]=范围内的ptr(新obj()); 错误: boost::scoped_ptr<T>& boost::scoped_ptr<T>::operator=(const boost::scoped_ptr<T&g

我有下面的代码,第2行在编译过程中给了我一个错误。是否可以创建作用域指针的映射,还是必须使用共享指针

map<int, scoped_ptr> mp;
mp[1] = scoped_ptr(new obj());
map-mp;
mp[1]=范围内的ptr(新obj());
错误:

boost::scoped_ptr<T>& boost::scoped_ptr<T>::operator=(const boost::scoped_ptr<T>&) [with T = ]’ is private
boost::scoped_ptr&boost::scoped_ptr::operator=(const boost::scoped_ptr&)[with T=]是私有的

你不能,
boost::scoped_ptr
是设计的(重点是我的):

作用域_ptr模板是满足简单需求的简单解决方案。它提供了一个基本的“资源获取即初始化”功能,没有共享所有权或所有权转移语义。它的名称和语义的强制(通过不可复制)都表明其仅在当前范围内保留所有权的意图

<强> SeopEdTpTR不能用于C++标准库容器中。如果需要智能指针,请使用共享\u ptr。

但是,您可以将
shared_ptr
s放置到容器中,因为在这种情况下不会执行复制:

std::list<boost::scoped_ptr<MyClass>> list;
list.emplace_back(new MyClass());
std::list;
list.emplace_back(新的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];

}
见C++外壳:


但是,我建议您不要这样做。

boost::scoped_ptr
std::unique_ptr
?C++11?如果您没有访问C++11的权限,请使用boost::ptr_容器。它满足您的需要。这是否意味着作用域指针不能与容器一起使用?@mlmostafa,是的,文档中明确说明您不能在标准库中使用它containers@SingerOfTheFall我认为你需要进一步澄清这一点。它们是可以使用的,您只需要小心地移动/放置
范围的ptr
s,而不是复制它们。
589