Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
557 views
in Technique[技术] by (71.8m points)

constructor - 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

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 :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...