map< string, Obj > vs map< string, Obj* >

let's discuss advantages and disadvantages of map< string, Obj > vs map< string, Obj* >

when do you use one vs the other? do you use a simple rule like if Obj is POD (plain-old-data), you use Obj - otherwise if class/struct, Obj*?

please contribute pros and cons, and I will add your comments to the OP - ty

==================================================================
map< string, Obj >

- initial copy-construction expensive for large Obj
+ easy memory: when out of scope, goes away
+ more explicit/self-contained in terms of ownership
+ read a bit faster since no indirection needed
- may require a default constructor
=====================================================================
map< string, Obj* >

+ insertion/copying is cheap: only a pointer
- have to think about ownership issues for new/delete
+ more flexible: actual Obj can live else-where
- requires extra indirection
+ can take-advantage of memory pools if you create a gazillion Obj (requires new)
=====================================================================
*cough*
std::map <std::string, std::unique_ptr<Obj>>;
*cough*

-Albatross
how does std::unique_ptr<> interact with boost::singleton_pool<>?

I've used unique_ptr<> a long time ago, after getting burned by auto_ptr<> - I need to read up more on it before using it...

btw, I don't think it's thread-safe, right?

anything I need to watch out for when using unique_ptr?

edit: unique_ptr<> is essentially one owner? lhs becomes the owner?
edit: does valgrind behave or does it choke on unique_ptr<>?
Last edited on
unique_ptr is... somewhat thread-safe, because of its "uniqueness". Unfortunately, there is a way to get around it...

Something you would need to watch out for is that std::unique_ptr is a C++0x feature, so... be sure you use the appropriate compiler and flags. ;) Also, if you're relying on the unique_ properties of a unique_ptr, do note that there are ways to accidentally (or deliberately) circumvent these properties, such as unique_ptr::get().

Also...
[It] stores a pointer to an owned object. The object is owned by no other unique_ptr.


Finally, I don't know how valgrind works with unique_ptr. Sorry. :(

-Albatross
It doesn't matter whether or not unique_ptr is thread-safe (it isn't) because std::map<> isn't thread-safe.

For me, the answer is very simple: store pointers only when polymorphism is required or the object to be stored is non-copyable, and then, use boost::ptr_map instead of std::map.

valgrind knows nothing about the source language of the executable; it will work just fine.
Topic archived. No new replies allowed.