Mehdi said:
Hi folks,
I'm new to Managed C++. I would like to know how can I implement a
function like this:
CWhateverClass **GetPointer()
{
//how can I allocate memory on heap (for my local variable of type
CWhateverClass),
//so that it won't go away when the
//local variable is out of scope.
}
You don't allocate memory, instead, you create objects. If you think in
terms of objects and object references then it makes life far easier. The
nuts and bolts of memory allocation are the responsibility of the GC, not
you!
With that in mind you don't need a pointer to a pointer, instead try this:
CWhateverClass __gc * GetPointer()
{
CWhateverClass __gc * obj = __gc new CWhateverClass;
// stuff
return obj;
}
// other code
CWhateverClass __gc * ptr = GetPointer();
// [1]
The point is that the __gc object is created on the managed heap, and a
*reference* to that object is returned. At the end of the method there are
two references, and once the stack has been cleared the local variable obj
goes out of scope and hence only the reference ptr will exist. However,
since at least one reference to the object exists it means that *if* a
garbage collection occurs at point [1] then the object will not be removed.
Note that my terminology is a little hazy here because at point [1] both the
reference ptr and obj will exist, but the GC will not be able to obtain the
reference obj (it will exist somewhere in memory, but the GC will not be
able to access it and so it is 'unreachable') and hence the GC ignores it.
Richard