简体   繁体   English

c ++:在if中分配变量

[英]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对象。 Model objects are quite big and I don't want to allocate one when not needed. Model对象非常大,我不想在不需要时分配一个。 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] 我有错误error: taking address of temporary [-fpermissive]

Do you see any workaround? 你看到任何解决方法吗? What is the C++ way of doing what I want to do? 做我想做的事的C ++方式是什么?

Do you see any workaround? 你看到任何解决方法吗? What is the C++ way of doing what I want to do? 做我想做的事的C ++方式是什么?

Use a smart pointer instead: 改为使用智能指针

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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