Search code examples
c++pointersif-statementallocation

c++: allocating a variable inside a if


I am working on some function, this function, depending on some parameters, might need a Model object. Model objects are quite big and I don't want to allocate one when not needed. Here is, in essence, what I want to do:

Model *myModel;
if (modelIsNeeded(arguments)) {
    myModel = &Model(arguments);
}

//processing ...

I have the error error: taking address of temporary [-fpermissive]

Do you see any workaround? What is the C++ way of doing what I want to do?


Solution

  • Do you see any workaround? What is the C++ way of doing what I want to do?

    Use a smart pointer instead:

    std::unique_ptr<Model> myModel;
    if (modelIsNeeded(arguments)) {
        myModel = std::make_unique<Model>(arguments);
    }