I am learning about smart pointers (std::auto_ptr
) and just read here and here that smart pointers (std::auto_ptr
) should not be put in containers (i.e. std::vector
) because even most compilers won't complain and it might seem correct. There is no rule that says smart pointers won't be copied internally (by vector
class for example) and transfer its ownership, then the pointer will become NULL. In the end, everything will be screwed up.
In reality, how often does this happen?
Sometimes I have vectors of pointers and if in the future I decide I want to have a vector of smart pointers what would my options?
I am aware of C++0x and Boost libraries, but for now, I would prefer to stick to a STL approach.
An alternative method uses a pointer to access the vector. w = new std::vector<int>(); The new operator creates a new, empty vector of ints and returns a pointer to that vector. We assign that pointer to the pointer variable w , and use w for the remainder of the code to access the vector we created with new .
You can store pointers in a vector just like you would anything else. Declare a vector of pointers like this: vector<MyClass*> vec; The important thing to remember is that a vector stores values without regard for what those values represent.
std::vector::data Returns a direct pointer to the memory array used internally by the vector to store its owned elements.
The C++ Standard says that an STL element must be "copy-constructible" and "assignable." In other words, an element must be able to be assigned or copied and the two elements are logically independent. std::auto_ptr does not fulfill this requirement.
Yes, you really can't use std::auto_ptr
with standard containers. std::auto_ptr
copies aren't equivalent, and because standard containers (and algorithms) are allowed to copy their elements at will this screws things up. That is, the operation of copying a std::auto_ptr
has a meaning other than a mere copy of an object: it means transferring an ownership.
Your options are:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With