簡體   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