[英]Conditional ? : operator with class constructor
有人可以解释一下为什么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
}
条件表达式的类型是两个分支的通用类型 ,其值类别也取决于它们。
true ? x2 : x1
true ? x2 : x1
, 常见类型是std::vector<int>
, 值类别是lvalue 。 这可以通过以下方式测试:
static_assert(std::is_same_v<decltype((true ? x2 : x1)), std::vector<int>&>);
true ? x2 : f()
true ? x2 : f()
, 常见类型是std::vector<int>
, 值类别是prvalue 。 这可以通过以下方式测试:
static_assert(std::is_same_v<decltype((true ? x2 : f())), std::vector<int>>);
因此,您在c1
中存储悬空参考。 对c1.var
任何访问都是未定义的行为 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.