But we don't need to deallocate the memory of vector or other STL containers ?
If you use the container like this:
std::vector<MyClass> v;
v.push_back( MyClass() );
//...
std::vector<MyClass> v;
v.push_back( MyClass() );
//...
To copy to clipboard, switch view to plain text mode
you don't need to de-allocate anything, vector will remove all of it's elements when it runs out of scope. But if you store pointers:
std::vector<MyClass*> v;
v.push_back( new MyClass() );
//...
std::vector<MyClass*> v;
v.push_back( new MyClass() );
//...
To copy to clipboard, switch view to plain text mode
then you need to remove the objects yourself. When vector runs out of scope it still removes all of it's elements, but this time no ~MyClass destructor is called - since it's just a pointer that is removed - and if you don't do proper cleanup yourself, you'll have a memory leak.
Does it mean that as soon as the
object created on the stack runs out of scope, it's memory on heap is deallocated automatically ?
class A{
public:
A(){
b = new B();
}
~A(){
}
B * b;
};
//...
{
A a;
} // a (created on stack) goes out of scope here...
class A{
public:
A(){
b = new B();
}
~A(){
}
B * b;
};
//...
{
A a;
} // a (created on stack) goes out of scope here...
To copy to clipboard, switch view to plain text mode
... but a.b (object created on heap) will not be removed automatically, you need to call "delete b" yourself.
Bookmarks