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:
- What, exactly, is different between pointers and
unique_ptrs besides automatic memory collection?
- How would I go about removing a
unique_ptrfrom 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
- Nothing. A
unique_ptris just a wrapper around a pointer, which deletes the pointer when the
unique_ptris destroyed. It has no overhead (just like the
auto_ptrtemplate it replaces).
- Nope -- it will just work. The difficulty actually comes from insertando the pointer into the vector or map -- whereas you must movimiento esta
unique_ptren el recipiente.
The difference is that unique_ptr obeys move semantics. Further, as the name suggests, you can't make copies of it.
Erasing an element of
std::vector<std::unique_ptr<T> >will effectively delete whatever that pointer pointed at.