Hi,
How can we delete the objects initialised by the pointers automatically in a program without delete[]/delete keyword. Like for example java explicitly runs the garbage collector. Can we do that same way somehow??
thank you.
Printable View
Hi,
How can we delete the objects initialised by the pointers automatically in a program without delete[]/delete keyword. Like for example java explicitly runs the garbage collector. Can we do that same way somehow??
thank you.
No, in C/C++ you don't have a garbage collector. In these languages you have to do most of the stuff by yourself. That's why they're so powerful (and not very good for begginers).
Although I think there is some third-party code you can add to your app to make a sort of garbage collector, they're very slow. Wouldn't recommend it. Besides, it's a good practice to tidy up after you, even in programming.
Use something from the standard library like an auto_ptr...
Code:#include <memory> //for auto_ptr
#include <iostream>
using namespace std;
template <class T>
ostream& operator<< (ostream& strm, const auto_ptr<T>& p)
{
if (p.get() == NULL)
strm<<"NULL";
else
strm<<*p;
return strm;
}
int main(void)
{
int x;
auto_ptr<int> aPtr(new int); //create an auto_ptr object and allocate mem
*aPtr=1;
cout<<aPtr<<endl; //only works with overloaded << operator
auto_ptr<int> aPtr2(aPtr); //now aPtr2 is equal to aPtr
cout<<aPtr<<endl; //ERROR now aPtr is deleted
cout<<aPtr2;
//the end
cin>>x; //just a quickie pause
}
MSVC++ .NET has a garbage collector. I haven't had any problems with using it although typically I like to clean up after myself anyway.
Are you talking about managed or unmanaged code? Because if your talking straight C++ there is no garbage collector.Quote:
MSVC++ .NET has a garbage collector.
Here is a simple garbage collector example I wrote on the C board. Unfortunately, it hasn't been compiled, so you're on your own debugging-wise. But the basic concept is simple:
1) store the address of the pointer.
2) store the data that the said pointer points to.
ie:
char * ptr = new char[10240];
(1) char ** pa = &ptr;
(2) char * p = ptr;
So that:
if(*pa != p) delete [] p;
Of course you'll need a list or vector of these memory managers.
Also, you can set up the garbage collection in a low-priority thread, but in most cases, there's no real justification to do so.