New Pointer Object and leaking?

So let say we set up a vector. Then we push_back an instance of our first custom class.

1
2
3
vec.push_back(new Ccustom1(24));

std::cout << vec[0].custint  /// shows 24 


Now say for some reason I need to replace this with a brand new instance. Do i just say

vec[0] = new Ccustom1(2);

or will that leave the old instance in memory causing unforeseen problems?

Is that the proper way to do this?
I don't believe that will call the constructor, this will however.

delete vec[0];
vec[0] = new Ccustom1(2);

If you ever need to see whether something is being destructed, either place a breakpoint inside constructor, or just go:
~Ccustom1()
{
std::cout << "Destructed" << std::endl;
}
Last edited on
You meant "destructor".

Alternatively, check out boost. The STL only cleans up the resources that it allocates internally. Generally if you call operator new then it is up to you to call operator delete. the vector, in that case, only allocates memory to hold pointers but doesn't know where the memory for the objects pointed to came from.
http://www.boost.org/doc/libs/1_45_0/libs/ptr_container/doc/ptr_container.html
Topic archived. No new replies allowed.