Re: Slow manual 'garbage collection' in C++ ??
On Jun 17, 2:30 pm, brey_maastri...@hotmail.com wrote:
But when I dont use pointers in my vector of vectors but only
vector<vector<nDimensionalPoint> >, the destructor of the objects
nDimensionalPoint are called, I suppose ?
Yes. When an object is declared "on the stack" (as opposed to "on
the heap" as pointer memory usually is), its destructor automatically
gets called when the object goes out of scope. Therefore, there is no
need to "garbage collect" it.
Take a look at this class:
class A
{
A() { std::cout << "In A's constructor.\n"; }
~A() { std::cout << "In A's destructor.\n"; }
};
Both of the following lines will call A's constructor:
A a; // calls A::A()
A *aPtr = new A; // also calls A::A()
But when do the destructors get called? Well, for aPtr, it gets
called when you delete() it, like this:
delete(aPtr); // invokes A::~A()
As for the object/variable named "a", its destructor gets called as
soon as it goes out of scope. If you return or break out of the scope
prematurely, its destructor still gets called! In other words, a's
destructor is guaranteed to get called once (and exactly once),
whereas aPtr's destructor gets called only when the "delete(aPtr);"
line is encountered. (If it's never encountered, aPtr's destructor
never gets called, and if it gets encountered more than once, a double-
delete() will happen, likely causing your program to crash.)
So you have to make sure that if you call new() on a pointer to
call delete() on it once and exactly once. But if you just declare it
on the stack (that is, as a non-pointer), you don't have to remember
to call anything for it -- it will clean itself up as soon as it goes
out of scope!
This aspect of C++ (that allows out-of-scope objects to clean
themselves up by calling their destructor) is one of the reasons C++
doesn't have a garbage collector. There is just no need for one if
you write your objects to be self-cleaning. (And you don't need to
define a destructor for a class if all the objects that class are
already self-cleaning.)
In fact, C++'s approach in cleaning objects when they go out of
scope is often much faster than many other languages' approach --
namely, to use a garbage collector that activates only when a system
process decides to.
So my advice is to avoid using pointers as well as calls to malloc/
new and free/delete. Doing so will prevent many memory leaks and
crashes, and in many cases make your code easier to read.
I hope this helps, Brey.
-- Jean-Luc