Inserting complex structures into containers on stack


What is the best way to create complex structures/objects in a method and insert them into an STL container that is defined outside the method, while keeping everything on the stack? The STL insert/push_* functions don't make a deep copy of objects.

The only way, I am aware of, is inserting a dummy object into the container, getting a reference to it and then using "swap" to swap the actual data for the dummy data, but that seems unnecessarily complicated and ugly. Is there a better way? Is such a situation generally an indicator, that I should not bother with keeping things on the stack and use heap memory instead?

... and off-topic: Can anyone recommend a book that specifically explains things, people, who are used to higher-level languages (Java in my case) and automatic memory management stumble upon and best practices, how to handle things like memory management, object ownership etc?

Thank you,

Why is it so important to keep everything on the stack? None of the standard containers (except std::array) store their elements on the stack. If you want to have a collection of elements on the stack you are forced to use a stack allocated array.

Insert and push_back will use the copy constructor to copy the objects. Just define the copy constructor to do deep copying if that is how you want the objects to be copied.
The STL insert/push_* functions don't make a deep copy of objects.
They do if you provide a deep copy operator for those objects. If you have a pointer then dereference the pointer *p for deep copy
Topic archived. No new replies allowed.