Is is possible to use std::map in C++ with a class without any copy operator?

后端 未结 3 1778
梦毁少年i
梦毁少年i 2020-12-17 16:32

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 objects

相关标签:
3条回答
  • 2020-12-17 17:22

    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());
    
    0 讨论(0)
  • 2020-12-17 17:24

    Not in C++03. How are you going to get the object from wherever it is now into the map without a copy constructor?

    In C++0x then you could move into the map, and in theory, perfectly forward to construct one in place from other arguments.

    Edit: You could swap it, if it's swappable, and you can default construct it in-place using operator[].

    std::map<int, Object> objmap;
    objmap[2]; // Default-constructs an Object in-place
    std::swap(objmap[2], Object()); // Swaps it into the map.
    
    0 讨论(0)
  • 2020-12-17 17:24

    Since your object is not copy-constructible, you could create your map containing shared_ptr :

    std::map<int,shared_ptr< Object > >
    

    That takes care of destruction of objects.

    0 讨论(0)
提交回复
热议问题