Question

Stack^ my_stack=gcnew Stack;
my_class^ a=gcnew my_class;
my_stack->Push(a);
my_stack->Push(gcnew my_class);
my_stack->Pop(); //will it cause memory leak?
a=gcnew my_class;
my_stack->Pop(); //will it cause memory leak?

sorry that the code is not tested. But I guess you all get what I mean here. when you pop a pointer, you lose the pointer; will the memory be released? there is also a method my_stack->Clear() which is also confusing for me.

Any help would be appreciated.

edit:

@Konrad Rudolph

Would the Pop() method call the destructor itself or the clr will automatically retrieve the memory space?

Konrad Rudolph also suggests me to consider using generic collection classes only.

For the new System::Collections::Generic::Stack<T> It says 'Removes and returns the object at the top of the Stack' And if so, what if I have another pointer pointed to object before? that is,

my_class^ a=gcnew my_class;
Stack<my_class>^ my_stack=gcnew Stack<my_class>;
my_stack->Push(a);
my_stack->Pop(); //what is a now? nullptr?
Was it helpful?

Solution

Pop does not call the destructor. You can use something like

T *topObject = my_stack->top();
my_stack->pop();
delete topObject;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top