简体   繁体   中英

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_ptr s. 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_ptr s 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?
  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.
  1. The difference is that unique_ptr obeys move semantics. Further, as the name suggests, you can't make copies of it.

  2. Erasing an element of std::vector<std::unique_ptr<T> > will effectively delete whatever that pointer pointed at.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM