Quick Q: Does using std:: smart pointers mean not using raw pointers? -- StackOverflow

Save to:
Instapaper Pocket Readability

Quick A: No. Smart pointers are for ownership. Raw pointers are still fine for non-owning pointers to an object that outlives the pointer.

C++11 Smart Pointer Semantics

I've been working with pointers for a few years now, but I only very recently decided to transition over to C++11's smart pointers (namely unique, shared, and weak). I've done a fair bit of research on them and these are the conclusions that I've drawn:

  1. Unique pointers are great. They manage their own memory and are as lightweight as raw pointers. Prefer unique_ptr over raw pointers as much as possible.
  2. Shared pointers are complicated. They have significant overhead due to reference counting. Pass them by const reference or regret the error of your ways. They're not evil, but should be used sparingly.
  3. Shared pointers should own objects; use weak pointers when ownership is not required. Locking a weak_ptr has equivalent overhead to the shared_ptr copy constructor.
  4. Continue to ignore the existence of auto_ptr, which is now deprecated anyhow.

So with these tenets in mind, I set off to revise my code base to utilize our new shiny smart pointers, fully intending to clear to board of as many raw pointers as possible. I've become confused, however, as to how best take advantage of the C++11 smart pointers. ...

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.