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

后端 未结 9 597
隐瞒了意图╮
隐瞒了意图╮ 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:55

    Based on comments, this only works for Microsoft C++ compilers

    Quite simply, without new:

        imguistate = (int *)malloc(ImGui::GetInternalStateSize());
        memset(imguistate, 0, ImGui::GetInternalStateSize());
        ((ImGuiState *)imguistate)->ImGuiState::ImGuiState();
    

    This works with any class:

    class SomeClass {
    public:
        SomeClass() {
            printf("Called constructor\n");
        }
    };
    
    int main () {
        SomeClass *someclass = new SomeClass;
        someclass->SomeClass::SomeClass(); // call constructor again
    }
    
    0 讨论(0)
  • 2020-12-02 10:56

    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.

    0 讨论(0)
  • 2020-12-02 10:58

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

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

    0 讨论(0)
  • 2020-12-02 10:59

    You can call a destructor, but memory will not be reclaimed, and your call will be equivalent to a function call. You have to remember that underneath the destructor does 2 things: destructs object based on your specification, and reclaims the memory. Since you dtor will be called anyway for an object allocated on the stack, calling it twice may result in an undefined behavior.

    0 讨论(0)
  • 2020-12-02 11:02

    Literally speaking, NO, you can't do it without the "new" keyword. See all the answers about placement new for the way to use the "new" keyword to call the constructor without actually allocating memory.

    0 讨论(0)
  • 2020-12-02 11:03

    Yes, using placement new - as above, but you might consider having a second factory class to manage the storage, even if it means copying an object. memcpy() is generally cheap for small objects.

    0 讨论(0)
提交回复
热议问题