user3091275
user3091275

Reputation: 1023

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?

Upvotes: 3

Views: 54

Answers (1)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

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);
}

Upvotes: 7

Related Questions