Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

manual object constructor call

Can you please tell me if it is possible to call object constructor manually? I know it's wrong and I would never do something like that in my own code and I know I can fix this problem by creating and calling initialization function, however the problem is that I stumbled at a case where there are thousands of lines of code in object's and its parents' constructors...

class MyClass()
{
    MyClass() { }
    virtual ~MyClass();

    void reset()
    {
         this->~MyClass();
         this->MyClass::MyClass(); //error: Invalid use of MyClass
    }
};
like image 947
Ryan Avatar asked Dec 28 '22 20:12

Ryan


2 Answers

You can still move construction/destruction into separate functions and call those directly. i.e.

class MyClass {
public:
    MyClass() { construct(); }
    ~MyClass() { destruct(); }

    void reset() {
        destruct();
        construct();
    }

private:
    void construct() {
        // lots of code
    }

    void destruct() {
        // lots of code
    }
};
like image 87
Ferruccio Avatar answered Jan 06 '23 00:01

Ferruccio


You could use placement new syntax:

this->~MyClass(); // destroy
new(this) CMyClass(); // construct at the same address
like image 45
sharptooth Avatar answered Jan 06 '23 00:01

sharptooth