【发布时间】:2019-04-26 04:12:21
【问题描述】:
有人可以解释一下为什么c 和c1 的构造方式不同。
我了解我参考了由“?”创建的副本运算符,在构造后被销毁,但为什么在第一种情况下它的行为方式不同。
我测试了它是否优化,但即使从控制台读取条件,我也有相同的结果。提前致谢
#include <vector>
class foo {
public:
foo(const std::vector<int>& var) :var{ var } {};
const std::vector<int> & var;
};
std::vector<int> f(){
std::vector<int> x{ 1,2,3,4,5 };
return x;
};
int main(){
std::vector<int> x1{ 1,2,3,4,5 ,7 };
std::vector<int> x2{ 1,2,3,4,5 ,6 };
foo c{ true ? x2 : x1 }; //c.var has expected values
foo c1{ true ? x2 : f() }; //c.var empty
foo c2{ false ? x2 : f() }; //c.var empty
foo c3{ x2 }; //c.var has expected values
}
【问题讨论】:
标签: c++ c++14 conditional-operator