is this a valid delete operation in c++?
I have a vector<some_struct&> array
in my code, and whenever I want to add some object to my vector I use array.push_back(*new some_struct)
. now I'开发者_C百科m wondering if I should delete every object in my array before clearing my array (using delete &array[i]) or not?
vector<some_struct&> array
is invalid, period.
The type (or types) with which you instantiate a Standard Library container must be object types. A reference type (like some_struct&
) is not an object type.
By definition, "containers are objects that store other objects" (from §23.1/1 in both C++03 and C++0x). References are not objects.
The behavior is undefined if you instantiate a container with a type that does not meet the requirements that the container imposes: your code may or may not compile and if it does compile, who knows what the result will be; anything could happen..
How does this even compile? That's not legal C++ code on any compiler I've used in the past 5 years.
The vector reference says that push_back copies the data to the container. In your example, not the pointer to, but the contents of each structure would be copied. So if you use *new my_struct, the reference to the memory allocated for the structs will be lost after having used them to pass the data to the container, meaning you need to store those pointers to each of the structs you allocated somewhere to be able to release them, or you will get memory leaks.
If you wanted to keep the pointers, the container should be a vector<some_struct*>
, and you could pass new some_struct
and should (e.g.) release them with delete array [i]
.
If your vector is declared vector<some_struct&> array
, array.push_back(new some_struct)
shouldn't work. array.push_back(some_struct())
will work and in that case you don't need to call delete.
You're going to lose the memory allocated every time you do this. You're essentially creating a copy of that data, but the original is lost in memory somewhere once this process completes. Either keep an external reference to it somewhere which you can delete after you copy it, or use a vector of pointers, not references.
精彩评论