是否可以使用std :: map在C ++与没有任何复制操作符的类? [英] Is is possible to use std::map in C++ with a class without any copy operator?
问题描述
我使用没有任何复制操作符的类(对象):它基本上不能被复制现在。我有一个
I'm using a Class (Object) that doesn't have any copy operator : it basically cannot be copied right now. I have a
std :: map< int,Object> objects
变量,用于列出带有int标识符的对象。我如何添加一个对象到这个地图,而不必使用复制操作符?
我尝试过
variable that lists objects with an int identifier. How could I add an Object to this map without having to use copy operators? I tried
objects.insert(std :: pair< 0,Object()>);
但不会编译。我只是想使用默认构造函数在地图中创建我的对象,但写
but that won't compile. I would just like to create my object initially inside the map using the default constructor, but writing
objects [0];
failed ...
感谢:)
objects[0];
fails...
Thanks :)
推荐答案
在C ++ 03中,存储在STL容器必须可复制。这是因为STL容器的 std :: allocator
实际上使用了 new
运算符的放置版本来构造对象在预分配的内存块中,并且需要存在一个复制构造函数来将要添加到容器中的对象的实际实例复制到容器的分配器预先分配的内存地址中。所以你唯一的选择是存储指向你的对象的指针,而不是对象本身。因此,您可以执行以下操作:
In C++03, objects that are stored in STL containers must be copyable. This is because a STL container's std::allocator
actually uses the placement version of the new
operator to copy construct the objects in pre-allocated memory blocks, and that requires the existence of a copy-constructor to copy the actual instance of the object you're wanting to add to the container into the memory address that had been pre-allocated by the container's allocator. So your only option would be to store pointers to your objects rather than the objects themselves. Therefore, you could do the following:
std::map<int, std::shared_ptr<Object> > objects;
objects.insert(std::pair<int, std::shared_ptr<Object> >(0, new Object());
这篇关于是否可以使用std :: map在C ++与没有任何复制操作符的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!