15

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

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]; fails... Thanks :)

1
  • 1
    std::map needs to store some sort of value. If not a copy of Object, perhaps a pointer to Object, assuming the Object isn't going to go away. Commented Jun 3, 2011 at 18:50

3 Answers 3

12

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());
Sign up to request clarification or add additional context in comments.

2 Comments

Would give an upvote- if you were using smart pointers. Manual deletion code is badness.
Well, that's what I did. Thank you very much, it works perfectly.
6

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.

1 Comment

This would be the perfect solution, but objmap[2] just won't compile : /usr/include/c++/4.4/bits/stl_pair.h:84: error: no matching function for call to ‘Object::Object(const Object&)’
3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.