manual object constructor call

亡梦爱人 提交于 2020-01-13 11:29:48

问题


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
    }
};

回答1:


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
    }
};



回答2:


You could use placement new syntax:

this->~MyClass(); // destroy
new(this) CMyClass(); // construct at the same address



回答3:


A constructor is called using placement new

new (address) MyClass();

This constructs a MyClass in an empty space at address.

Would never do this inside the class though!

Edit
If you already have an object of the right type, and want to assign it default values, an alternative is

*this = MyClass();

which creates a new object with default values and assigns that value to your existing object.



来源:https://stackoverflow.com/questions/6031470/manual-object-constructor-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!