Tom
Tom

Reputation: 1057

C++11 smart pointers always instead of new/delete?

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?

Upvotes: 6

Views: 3086

Answers (2)

Arun
Arun

Reputation: 2102

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.

Upvotes: 2

Cubic
Cubic

Reputation: 15703

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.

Upvotes: 7

Related Questions