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

前端 未结 10 1582
情深已故
情深已故 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 16:55

    I think you can explicitly call the destructor if you make sure that the instance is replaced/recreated with a call to placement new:

    class c
    {
    public:
       void add() ;
       c();
       ~c() ;
    };
    
    int main()
    {
     c objC  ;
     objC.add() ;
     objC.~c() ; // this line compiles
     new (&objC) c;  // placement new invokes constructor for the given memory region
    }
    

    I've never seen this in practice, but logically it should work (unless c's constructor can throw, in which case, I imagine, hell could break loose during stack unwinding).

    However, what you probably want is just assignment:

    objC = c();
    

    If the destructor has side-effects that you are interested in, implement assignment using the copy-and-swap idiom which gets the destructor invoked for the "left-hand" value.

提交回复
热议问题