-1

I'm new to C++/CLI, and would like a clarification on memory free up.

Imagine a scenario, where :

sampleServer srv = new sampleServer()
while(true)
{
    ABC newObject = srv.getItem();
}

ABC^ sampleServer::getItem(){ return gcnew ABC(//LIST OF some parameters);}

Now here, unless a Dispose is called by newObject, because of a continuous stream of new objects which are being returned and not getting freed up, memory will continue to be allocated, but not released.

If I do not wish to call the DIspose, the only other way is to have finalizerstaking care of the memory free up.

However, considering class sampleServer, it does not have the object of class ABS as one of its members. It is still able to return a new instance of it, because of the to classes being in the same namespace.

So if I am considering class sampleServer, what am I supposed to call the Finalizer on?

And if the thought process is incorrect, how would I free up memory in the case given above?

user1173240
  • 1,455
  • 2
  • 23
  • 50

1 Answers1

0

Since you are using gcnew with ABC, it must be a ref class.

Then, your compiler should be giving you:

'*' : cannot use this indirection on type 'ABC'

Now, suppose you fix that by replacing the syntax for the C++ * type modifier with the CLI ^ handle syntax, you effectively have:

while(true)
{
    ABC^ newObject = srv->getItem();
}

The scenario you are considering does not exist. When newObject goes out of scope, the object it was referencing is not reachable by sweeping through connected objects from the garbage collection root object(s). So, when the garbage collector runs[1], all of the objects can be freed.

With a system of garbage collected objects, memory resources are handled by the system. You only need to concerned about resources that objects hold that are outside of the system. That would include "native heap" memory obtained through malloc or new, handles to various objects obtained through the operating system (file descriptors, sockets, windows, etc).

In your classes, you haven't shown any so-called "native resources" or any recursive ownership of native resources.

[1] Theoretically, except for performance reasons, the garbage collector need not run until no more virtual memory can be committed (e.g., the system is out of disk space). So, don't go looking at memory usage unless you are evaluating the garbage collector.

Tom Blodget
  • 20,260
  • 3
  • 39
  • 72