4

I would like to pass pointers to d around from one container to a next. At no point will there be more than one owner of the pointer (or d itself). I'd like that when the last pointer goes out of scope, delete d automatically called.

In C++11, I'd do this with unique_ptr. But, alas, I can't use C++11. What is the best equivalent in C++? Boost is fine. Or, if there is none, what is the appropriate way to handle this?

SRobertJames
  • 8,210
  • 14
  • 60
  • 107
  • 2
    " I'd like that when the last pointer goes out of scope, delete d automatically called." That doesn't sound like `unique_ptr`'s functionality, but more like `shared_ptr`'s. – juanchopanza May 26 '15 at 06:56
  • `shared_ptr` is also new in C++11. So either way, if you don't have a C++11 compiler, you have to use Boost or similar third-party library, or write your own smart pointers. – Remy Lebeau May 26 '15 at 06:59
  • `uinque_ptr` is very similar to `shared_ptr`, except it assumes a single owner, so the pointer is moved around instead of being copied. – Nathan Fellman May 26 '15 at 07:03
  • Take care to look at this answer updated for newer releases of Boost: http://stackoverflow.com/a/28193068/4213662 – Persixty May 26 '15 at 07:04

1 Answers1

4

Well, boost::movelib::unique_ptr is part of the Boost.Move library which offers "Portable move semantics for C++03 and C++11 compilers". Since unique_ptr clearly needs move semantic, this looks like your best choice.

Shoe
  • 74,840
  • 36
  • 166
  • 272