Reputation: 2541
there is an object like :
std::map<std::string, MyClass> data;
where MyClass is an expensive to copy. at some application runflow moment, I need to perform an operation which retrieves MyClass object by key (usual operator[]) but I need to tear this object off from a container. direct solution is a copying to local variable and erase in a container after that. But a copying is a heavy operation for MyClass. Is there way (probably in C++11 terms) to avoid a copying/deleting? probably some move semantics from container to local variable? not sure how to do this.
Upvotes: 2
Views: 43
Reputation: 510
There are two good ways to handle this that I can immediately think of. Probably the simplest, is to define data as
std::map<std::string, MyClass*> data;
This means that it now holds pointers. You would have to instantiate elements of MyClass yourself, store in your map, and then remove from the map without ever effecting the underlying object itself. Smart pointers can simplify object management if it's your preference.
The other way is to implement move semantics for MyClass and make sure that MyClass' move operator is more optimized. If conducting a move operation on all of the class members is still to expensive, a fairly effective way to make a very fast move operator is to have MyClass maintain a pointer to a struct that holds all of it's data and during class construction initiailize the pointer and delete it in the destructor. Your move operator at that point is really just a matter of moving the pointer from the source to the destination. This unfortunately adds a level of indirection for all of your other operations in MyClass.
Upvotes: 1