0
Related to C++
Please inform me. In case we write a class and it use default constructor and destructor. How do we know that it currently executing or already executes the ~destructor? For example we can identify that destructor is run by the presence of instruction delete *pointer to show ~destructor is executed and obkect is destroyed.
3 Antworten
+ 3
When you reach the } that is at the same level of your object, thats when the destructor is called.
{
Object o;
{
...
}
} o's destructor called.
After the destructor is called, the object is not even in scope anymore.
Unless you're using placement new ( which you shouldn't unless you're a master at C++ ) or unions, you really shouldn't worry about that.
( In case you're curious )
https://en.cppreference.com/w/cpp/language/new#Placement_new
+ 3
You can explicitly define a destructor for class.
it'll be called when object goes out of scope or is deleted.
for example.
class Cat{
string name;
~Cat(){
std::cout<<this.name <<" is dead"<<std::endl;
}
};
it'll let you know when it's called which may not be possible with the default destructor.
I have a code ,maybe not completely related with what you are asking but can be bit helpful:
this will help you understand that objects instantiated on stack within same scope are destroyed in reverse order of creation.
https://code.sololearn.com/caXq8SN4PfpY/?ref=app
also you can check this:
I used a static variable to keep track of no. of objects and you can print which object is deleted when.
https://code.sololearn.com/ckvqxZPZi108/?ref=app