6

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?

4
  • 15
    unique_ptr was designed to be a zero-cost abstraction. Learn to stop worrying and love the bomb. Commented Mar 15, 2013 at 12:45
  • 9
    How can we use smart pointers instead of new and delete. We have to use them with new, to avoid delete Commented Mar 15, 2013 at 12:46
  • 4
    @iammilind make_shared and I also use an implementation of make_unique. Of course that still uses new internally. Commented Mar 15, 2013 at 12:50
  • 1
    @iammilind yes I know, but you can't use delete without new, so I just wrote "new and delete" Commented Mar 15, 2013 at 12:57

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Point 2 isn't true. If one shared_ptr refers to an object containing a shared_ptr which refers somehow back to the first. You will have a memory leak. Edit: So you will still need to know what you're with or without the smart pointers.
Point 2 is true, cyclic references is a "valid" state. shared_ptr give you only that if ref_count == 0 its call delete.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.