What is the mechanism by which destructors are called on objects associated with the stack?
How does C ++ ensure that destructors are called on stack-related objects? What happens to the destructor function (or a pointer to it) when I assign dynamic memory like this:
class MyClass {
public:
~MyClass()
{
std::cout<<"Destructor called."<<std::endl;
}
MyClass()
{
std::cout<<"Constructor called."<<std::endl;
}
};
....................................................................
//Limit scope for example
{
MyClass instance;
}
The constructor and destructor are called. What's going on here?
source to share
You would not wonder why this
{
int i;
}
automatically creates and destroys i
, doesn't it? C ++ does a lot that allows you to create types that behave exactly like built-in types. And just like with built-in types, in C ++ (except, say Java or C #), this
{
MyClass instance;
}
does not simply define a link that can be attached to null
or to some actual object. It creates a real object.
Object creation takes place in two stages: first (when entering a region) raw memory is provided. Then (when an object definition is encountered) the constructor is called. For built-in types, no constructor is called. If you don't initialize a built-in variable, it has a random value. (Actually this is what the bit pattern was in the memory presented in step # 1.) Deleting an object also happens in two stages: first, the destructor is called (again, not for built-in ones), then the memory is returned to the time system execution.
(Note that providing and disposing of memory for stack variables is usually as cheap as building / decreasing a register).
source to share
Yes, both the constructor and the destructor are called. And more importantly:
{
MyClass instance;
throw "exception";
}
this example also calls the destructor. This is why I always prefer to allocate my objects on the stack (or at least wrap dynamic allocations with stack-allocated trustees).
source to share
Well it didn't call the destructor right after the constructor.
It calls this when it is about to terminate the program.
int main() {
MyClass obj;
cout<<"testing....1"<<endl;
cout<<"testing....2"<<endl;
return 0;
}
ans:
Constructor called.
testing....1
testing....2
Destructor called.
source to share