Automatic destruction of object even after calling destructor explicitly

后端 未结 5 1738
野趣味
野趣味 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:31

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

    The destructor will be called when the object gets out of scope, regardless of whether you call the destructor explicitly or not. Don't explicitly call the destructor for objects with automatic storage duration.

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

    Yes. When you initialize an object using the placement new expression, you need to call the destructor explicitly. Sample code from the above site:

    char* ptr = new char[sizeof(T)]; // allocate memory
    T* tptr = new(ptr) T;            // construct in allocated storage ("place")
    tptr->~T();                      // destruct
    delete[] ptr;                    // deallocate memory
    

提交回复
热议问题