Usando std :: unique_ptr con contenedores estándar

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?

preguntado el 09 de enero de 11 a las 03:01

Is unique_ptr an essential condition? If safety is your purpose, std::shared_ptr might be an alternative. -

2 Respuestas

  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 insertando the pointer into the vector or map -- whereas you must movimiento esta unique_ptr en el recipiente.

Respondido el 11 de diciembre de 12 a las 02:12

Thanks! I wasn't quite sure, and couldn't find much on Google, so I'm glad to get an answer. - OniLink

+1 for a good explanation, though you might want to note that at most one unique_ptr can point at a resource, while an unboundedly large number of raw pointers can point at a particular resource. - templatetypedef

+1, perhaps adding an example of insertion (especially one showing why move is required) would help. - Matthieu M.

  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.

Respondido el 09 de enero de 11 a las 06:01

+1 for 2. - obvious when you focus on it, but can be a problem during transitioning from raw pointers to smart pointers, if you only go "half way" with raw pointers pointing to freed memory because an item was removed - kfmfe04

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.