Why can I not call my class's constructor from an instance of that class in C++?

前端 未结 10 1520
情深已故
情深已故 2021-01-03 16:39

When can an object of a class call the destructor of that class, as if it\'s a regular function? Why can\'t it call the constructor of the same class, as one of its regular

10条回答
  •  别那么骄傲
    2021-01-03 17:16

    A destructor must be called on an existing instance of a class - destructing the instance is what it does. A constructor creates a brand new instance of a class, so calling on an existing instance makes no sense.

    This is similar to the way new and delete work:

    int * p = new int;    // call to new needs no existing instance
    delete p;             // call to delete requires existing instance
    

    And note in your code, the object would be destroyed twice, once explicitly, and once implicitly at the end of its enclosing scope. You typically only explicitly call a destructor if you are doing something unusual, probably involving the use of placement new.

提交回复
热议问题