In C++11 should we always use unique_ptr or shared_ptr instead of new/delete? How is it with performance, are smart pointers much slower?
2 Answers
unique_ptr doesn't (isn't supposed to) have any runtime overhead whatsoever compared to using raw pointers. shared_ptr does have some memory and time overhead (how much depends on the implementation). The practical overhead here can easily be zero if you actually need something that behaves like a shared_ptr (that is, no other implementation you'd think of would be any faster or more memory efficient).
That is not to say you'll never use new/delete in your code, but it's not something you'll do all the time.
Comments
I would prefer shared_ptr to handle the raw memory because-
1) It follows RAII and Counted body idioms.
2) Object is guaranteed to be destroyed, memory is released even if exception occurs.
3) No more choas of deciding when to new/delete.
2 Comments
shared_ptr give you only that if ref_count == 0 its call delete.
unique_ptrwas designed to be a zero-cost abstraction. Learn to stop worrying and love the bomb.newanddelete. We have to use them withnew, to avoiddeletemake_sharedand I also use an implementation ofmake_unique. Of course that still usesnewinternally.