简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM