Search code examples
c++constructorplacement-new

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


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

class Object1{
    char *str;
public:
    Object1(char*str1){
        str=strdup(str1);
        puts("ctor");
        puts(str);
    }
    ~Object1(){
        puts("dtor");
        puts(str);
        free(str);
    }
};

Object1 ooo[2] = {
     Object1("I'm the first object"), Object1("I'm the 2nd")
};

do_smth_useful(ooo);
ooo[0].~Object1(); // call destructor
ooo[0].Object1("I'm the 3rd object in place of first"); // ???? - reuse memory

Solution

  • Sort of. You can use placement new to run the constructor using already-allocated memory:

     #include <new>
    
     Object1 ooo[2] = {Object1("I'm the first object"), Object1("I'm the 2nd")};
     do_smth_useful(ooo);
     ooo[0].~Object1(); // call destructor
    
     new (&ooo[0]) Object1("I'm the 3rd object in place of first");
    

    So, you're still using the new keyword, but no memory allocation takes place.