user3091275 user3091275 - 1 year ago 46
C++ Question

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?

Answer Source

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);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download