简体   繁体   English

有条件的? :具有类构造函数的运算符

[英]Conditional ? : operator with class constructor

could someone explain me why c and c1 are constructed different way. 有人可以解释一下为什么cc1的构造方式不同。 I understand that I have reference to copy created by '?' 我明白我参考了'?'创建的副本 operator, which is destroyed after construction, but why in first case it behave other way. 操作员,在施工后被摧毁,但为什么在第一种情况下它表现出其他方式。 I've tested if its optimization, but even with conditions read from console, I have same result. 我已经测试过它的优化,但即使从控制台读取条件,我也有相同的结果。 Thanks in advance 提前致谢

#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
}

The type of a conditional expression is the common type of the two branches, and its value category also depends on them. 条件表达式类型是两个分支的通用类型 ,其值类别也取决于它们。

  • For true ? x2 : x1 true ? x2 : x1 true ? x2 : x1 , the common type is std::vector<int> and the value category is lvalue . true ? x2 : x1常见类型std::vector<int>值类别lvalue This can be tested with: 这可以通过以下方式测试:

     static_assert(std::is_same_v<decltype((true ? x2 : x1)), std::vector<int>&>); 
  • For true ? x2 : f() true ? x2 : f() true ? x2 : f() , the common type is std::vector<int> , and the value category is prvalue . true ? x2 : f()常见类型std::vector<int>值类别prvalue This can be tested with: 这可以通过以下方式测试:

     static_assert(std::is_same_v<decltype((true ? x2 : f())), std::vector<int>>); 

Therefore you are storing a dangling reference in c1 . 因此,您在c1中存储悬空参考。 Any access to c1.var is undefined behavior . c1.var任何访问都是未定义的行为

live example on godbolt.org godbolt.org上的实例

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

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