2016-09-17 149 views
0

它危險返回一個參考包裝紙等,顯示如下:返回C++參考包裝

std::vector<std::reference_wrapper<int>> foo() { 

    int x = 10; 

    std::vector<std::reference_wrapper<int>> vec; 
    vec.push_back(x); 
    return vec; 

} 

foo2() { 
    std::cout << foo()[0] << std::endl; 
} 

我假定本地/堆棧變量x可以在foo2()丟失。

+0

通常的懸掛指針/參考 –

回答

0

函數std::vector<std::reference_wrapper<int>> foo();從本質上返回一個向量,該向量引用位於已被銷燬的函數堆棧中的局部變量。一個懸掛引用的向量。這是未定義的行爲。