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

后端 未结 9 620
隐瞒了意图╮
隐瞒了意图╮ 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条回答
  •  北海茫月
    2020-12-02 10:56

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

     #include 
    
     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.

提交回复
热议问题