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

后端 未结 9 636
隐瞒了意图╮
隐瞒了意图╮ 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
    }
    

提交回复
热议问题