life span of dynamicaly allocated memory
Hi Guys,
Cinsider the code:
class MyClass { /*stuff*/};
void foo()
{
MyCalss variable;
Myclass *pointer = new MyClass;
/* do stuff */
}
Which of the following is correct:
1.At the end of the function scope, both, variable and pointer will be destryed, that includes automatic destructor call for pointer, and all memory use by both variable and pointer will be returned to the system
2.At the end of the function scope, Only variables memmory is returned to the system, while only the pointer it self is destroyed but the allocated memory stays, untill delete will be called for it explicitly.
I think 2 is correct - can any one second that?
If its true, it actualy means, that dynamic allocation is in fact static - since the momory stayes "reserved" untill explicit delete call.
I use to think all "things" that are not declared as "static" should be dedstryed on end of scope - including the memory they used...
Thanks for any replies.
All the best
Dani.
Self destruction in 10 seconds...
Dani,
This issue can often be a source of confusion. At the end of the function foo, "variable" will go out of scope and its destructor will be called. However, for the variable "pointer" it is a bit more confusing. The variable will go out of scope and it can no longer be used. But the destructor of the class will not be called and the memory reserved by the call to new will not be released.
This forces you to consider several things in your design. The programmer is responsible for the cleanup of pointers allocated in this fashion. There is a use of pointers called, I think, "smart pointers" which deal with this problem. Some other competent person should explain the theory behind smart pointers.
There is also an advantage to allocation and non-cleanup: New pointer elements can be added to lists in subroutines and manipulated beyond the scope of the subroutines. This can be very powerful for many design elements.
Chris.
:)
one extra "clarification"
To add to TheCPUWizard and Gabriel's earlier distinction between new and malloc, it is common practice to refer to the space of memory where "new" objects get created as the free store, so as not to confuse it with malloc's heap. Even though they are often the same memory, the free store and the heap are independent in the standard.