Automatic destruction of object even after calling destructor explicitly

后端 未结 5 1633
野趣味
野趣味 2021-01-23 09:05

The following program :

#include 
using namespace std;

class Test
{
public:
    Test() { cout << \"Constructor is executed\\n\"; }
    ~Te         


        
5条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-23 09:28

    This is not an "explicit call to constructor":

    Test(); // Explicit call to constructor
    

    It constructs a temporary object, which implicitly calls the constructor, then the temporary immediately goes out of scope, which implicitly calls the destructor. You can't explicitly call a constructor, it gets called implicitly when you construct an object.

    My question is even after explicitly calling destructor in main(), why does the compiler call the destructor implicitly before exiting main()?

    Because the compiler always destroys local variables. Just because you did something dumb (manually destroyed an object that gets destroyed automatically) doesn't change that.

    As a side question, apart from use in delete operator is there any other use of the strategy of calling destructor explicitly?

    It's used when managing the lifetime of objects in raw memory, which is done by containers like std::vector and other utilities like std::optional.

提交回复
热议问题