gpt4 book ai didi

c++ - 有条件的? : operator with class constructor

转载 作者:IT老高 更新时间:2023-10-28 23:13:02 26 4
gpt4 key购买 nike

谁能解释一下为什么 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
}

最佳答案

条件表达式的类型是两个分支的公共(public)类型,它的值类别也依赖于它们。

  • 对于true ? x2 : x1普通类型std::vector<int> 值类别左值。这可以通过以下方式进行测试:

    static_assert(std::is_same_v<decltype((true ? x2 : x1)),  std::vector<int>&>); 
  • 对于true ? x2 : f()普通类型std::vector<int>值(value)类别prvalue。这可以通过以下方式进行测试:

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

因此,您将悬空引用存储在 c1 中.任何访问 c1.var未定义的行为

live example on godbolt.org

关于c++ - 有条件的? : operator with class constructor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53448536/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com