| vietory (16) | |||
|
As I read in the reference page for std::vector clear function() " All the elements of the vector are dropped: their destructors are called, and then they are removed from the vector container, leaving the container with a size of 0." It saids that it would call all the of destructors of the erasing elements in side that vector when clear() is called. Just wondering if this is true? Because I went through with the GDB debugger it doesn't seem to call the destructors for them. Here a test code that I wrote just wondering will this give me memory leak if delete is not called.
if above is the case then what described in the description about clear is not true or am I missing something. | |||
|
Last edited on
|
|||
| ne555 (4385) | |
|
Yes, that's a memory leak. The vector does call the destructor of its elements. But in your example the elements are pointers, not objects. The destructor of a pointer does not delete it. Think about why this is the expected behaviour. | |
|
|
|
| vietory (16) | |
|
thanks for the reply so what is the proper way for the clear function to call its destructor | |
|
|
|
| TheMassiveChipmunk (259) | |
Use std::auto_ptr <T> or for the new C++0x standard use std::unique_ptr <T> .
| |
|
Last edited on
|
|
| ne555 (4385) | |
|
Again, it does call the destructors. In your example, you should simply std::vector<int> vect;If you need to use pointers because you want a polymorphic container, I know two possibilities: _ Use smart_pointers. As STL containers use copy mechanism (c++98) you will need shared_ptr _ Especialize a container to handle pointers. By instance boost::ptr_vector. I guess that you could simply modify the allocator used, making the destruct() method responsible for the delete, but I haven't tested that. | |
|
|
|
| vietory (16) | |||
so I guess why my way of copying vectors that are holding pointer elements also not working, even though I overload the = for that pointer element.
So I guess my question is what is a proper to copy std::vector<int*> thanks. or I have to manually do it like what I did with delete. thank-you | |||
|
|
|||
| ne555 (4385) | ||
If you want to copy the objects pointed, use copy_ptr
| ||
|
|
||
| vietory (16) | |
|
Hi thanks replying to my posts Would you so kind and give me a good example link on how to incoporate shared_ptr and copy_ptr with vector std thanks. | |
|
|
|