繁体   English   中英

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

[英]Conditional ? : operator with class constructor

有人可以解释一下为什么cc1的构造方式不同。 我明白我参考了'?'创建的副本 操作员,在施工后被摧毁,但为什么在第一种情况下它表现出其他方式。 我已经测试过它的优化,但即使从控制台读取条件,我也有相同的结果。 提前致谢

#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任何访问都是未定义的行为

godbolt.org上的实例

暂无
暂无

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

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