Object and object pointer destructor calling scheme

Asked 2 years ago, Updated 2 years ago, 26 views

Assume ClassName is a Test

Test fTest; Test *sTest;

Does the compiler automatically call destructors only for objects assigned to the stack? So the fTest calls the extinction on its own by the compiler?

In the case of sTest, which is an object pointer, the destructor must be called using the delete operator Is it because it's a hip area and it's not a compiler area?

I would like to know more about it because it simply says that the book or writing calls the extinction.

The compiler calls the destructor of the object only for the object created in the stack

In the former case, the extinction is called automatically, and in the latter case, I wonder if I have to call directly through the delete operator.

c++

2022-09-21 16:36

1 Answers

This question is more about the life cycle of the variable than the compiler.

A.

Test fTest;

A variable, such as the one above, usually exists only when it is in a function from the time it is declared to the end of the function. In other words, it's clear when it's born and when it's going to die.

That is, the life cycle of the variable = the life cycle of the object .

B.

Test *sTest;

As shown above, the pointer only manages the variable life cycle for the pointer itself. That is, some objects that the pointer will point to are governed by different rules.

For example, if the pointer sTest was pointing to fTest, it would only be valid for reference before the fTest was born and died, and it would no longer be valid after it died. And fTest and sTest are different variables, and just because the fTest pointed by sTest is extinguished, it does not affect sTest.

Depending on when you access the fTest through sTest, errors may occur and may operate normally.

This means that the pointer does nothing to the object life cycle.

C.

Another way to manage the life cycle is new and delete. Objects created by new are destroyed only when they meet delete. In this case, method of directly managing the life cycle of the object, so it is not related to the life cycle of the variable.

Typically, the local variable used during function operation exists in the execution stack, and the object assigned by new/delete exists in the heap.

Note that stack and heap are the ways to manage memory, and they just follow because C++ assumes a stack execution machine.


2022-09-21 16:36

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.