C++, is it possible to call a constructor directly, without new?

后端 未结 9 641
隐瞒了意图╮
隐瞒了意图╮ 2020-12-02 10:40

Can I call constructor explicitly, without using new, if I already have a memory for object?

class Object1{
    char *str;
public:
    Object1(c         


        
9条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-02 10:58

    Let me show you some code on how it can be done, both in construction and destruction

    #include 
    
    // Let's create some memory where we will construct the object.
    MyObject* obj = (MyObject*)malloc(sizeof(MyObject));
    
    // Let's construct the object using the placement new
    new(obj) MyObject();
    
    // Let's destruct it now
    obj->~MyObject();
    
    // Let's release the memory we used before
    free(obj);
    obj = 0;
    

    I hope the above summary makes things clearer.

提交回复
热议问题