以下是代码:
struct S
{
S() {}
void f();
private:
S(const S&);
};
int main()
{
bool some_condition;
S my_other_S;
(some_condition ? S() : my_other_S).f();
return 0;
}
gcc编译此代码失败,报错如下:
test.cpp: In function 'int main()':
test.cpp:6:5: error: 'S::S(const S&)' is private
test.cpp:13:29: error: within this context
我不明白为什么在那一行需要进行复制构造 - 目的只是在一个默认构造的S
实例或者my_other_S
上简单地调用f()
,也就是说应该等同于:
if (some_condition)
S().f();
else
my_other_S.f();
第一种情况有什么不同之处,为什么需要复制构造函数?
编辑:那么,在表达式上下文中有没有办法表达“在临时对象或预先存在的对象上执行此操作”?
f()
部分,实际上它可能是一个有许多参数的函数,每个参数可能都是一个冗长表达式的结果...你知道怎么回事。 - HighCommander4f()
返回值的变量,即您可以执行auto x = (some_condition ? S() : my_other_S).f();
,但您无法执行auto x; if (some_condition) x = S().f(); else x = my_other_S.f();
。我相信此时还有许多情况我没有想到的。 - HighCommander4