user2754413
user2754413

Reputation:

Why should I not use smart pointers?

The question may seem a bit basic, but what are downsides of smart pointers besides performance? And should I always use them for non-performance-critical code?

EDIT: I use Visual Studio 2013 RC and C++11

Upvotes: 0

Views: 1166

Answers (2)

leander
leander

Reputation: 8737

For e.g. a unique_ptr, there is unlikely to be any performance downside with any reasonable optimizing compiler. For shared_ptr you have potentially an extra heap alloc -- something you can solve with make_shared, and there's the cost of maintaining a refcount, but consider that if you are rolling your own tracking or lifetime management mechanisms you may be taking this kind of overhead as well. See GotW #89 for more discussion of this.

Re "should I always use them", Sean Parent expounds on this (and some subtleties) in the GoingNative 2013 talk C++ Seasoning -- his third goal is "no raw pointers", and he gives a number of examples. At one point he puts forth that shared_ptr-to-non-const is nearly equivalent to global variables... It's worth watching this. The C++ Seasoning slides are available, but I'd recommend watching it.

Generally speaking, each smart pointer is going to have tradeoffs, just as raw pointers have tradeoffs. It's going to be up to you to evaluate the situation and the tradeoffs and make a choice. And it seems that there are enough well-vetted smart pointer variants to match many if not most situations these days, especially with the refinements in C++11 and C++14.

Upvotes: 3

Dietmar Kühl
Dietmar Kühl

Reputation: 154025

I always use smart pointers to hold resources, even though the "smart" pointer may not be that smart, e.g., when using a std::unique_ptr<T> or std::unique_ptr<T[]>. When using pointers to model non-owning links or when passing non-owning pointers around I'm using raw pointers as they are the correct abstraction for this job and don't interfere with any choice made about how the object is owned.

Upvotes: 3

Related Questions