Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using std::unique_ptr with standard containers

I've been looking for a way to do safe vectors and maps of dynamic pointers, when I realized C++11 adds unique_ptrs. I looked into how to use them on Google, but have been unsuccessful in looking for details. What I need to know are the following:

  1. What, exactly, is different between pointers and unique_ptrs besides automatic memory collection?
  2. How would I go about removing a unique_ptr from a vector or map? Is there any special code I have to use besides erasing the iterator?
like image 918
OniLink Avatar asked Jan 09 '11 03:01

OniLink


1 Answers

  1. Nothing. A unique_ptr is just a wrapper around a pointer, which deletes the pointer when the unique_ptr is destroyed. It has no overhead (just like the auto_ptr template it replaces).
  2. Nope -- it will just work. The difficulty actually comes from inserting the pointer into the vector or map -- whereas you must move the unique_ptr into the container.
like image 91
Billy ONeal Avatar answered Sep 21 '22 15:09

Billy ONeal