C++中的短路评估和分配

kur*_*urt 1 c++

在C++中可能是这样的:

if (int* x = (foo() || bar()))
{
    // do something with x
}
else
{
    // do something else if both foo() and bar() return nullptr
}
Run Code Online (Sandbox Code Playgroud)

我知道代码不会编译(不能将bool转换为int*),但是有没有一个有效的等效"快捷"代码才能做到这种快捷方式?基本上,我想要的是如果foo()没有返回空指针,则将foo()的返回值赋给x.如果foo()产生一个空指针,则将bar()的返回值赋给x.

假设foo()和bar()是昂贵的计算,因此需要最小化对它们的调用次数.如果foo()没有产生空指针,那么理想情况下,不需要调用bar().

Aco*_*gua 5

使用新的C++ 17功能,应该可以实现以下功能:

if(int* x = foo(); x = x ? x : bar())
Run Code Online (Sandbox Code Playgroud)

Pre-C++ 17将要求你在外面声明x(以下通过避免自我赋值来改进上面;谢谢,N00byEdge):

int* x;
if(x = foo(), x ? x : (x = bar()))
Run Code Online (Sandbox Code Playgroud)

但是,可能在外面移动任务更好:

int* x = foo();
if(x ? x : (x = bar()))
Run Code Online (Sandbox Code Playgroud)

在上述所有情况下,编译器可能会警告您,您可能将赋值与比较混合(=而不是==); 为了使编译器知道要进行赋值,您可以在赋值周围添加其他括号...

编辑: Nice解决方案,由freestyle发布,遗憾的是仅作为注释(此处,由于赋值的优先级低于逻辑或者优先级,因此需要括号):

int* x;
if((x = foo()) || (x = bar()))
Run Code Online (Sandbox Code Playgroud)

假设C++ 17,这可能看起来像这样:

if(int* x; (x = foo()) || (x = bar()))
Run Code Online (Sandbox Code Playgroud)

或根据以下内容完善自己的答案:

if(int* x = foo(); x || (x = bar()))
Run Code Online (Sandbox Code Playgroud)

  • On,if(int*x = foo(); x = x?x:bar())`,不会`if(int*x = foo(); x?x:x = bar())`没有x的自我分配更好? (2认同)