![](/img/trans.png)
[英]Is passing const reference to a temporary string object safe in C++?
[英]C++ dangling const reference to a temporary object
為什么下面的代碼中有懸掛的參考? 我認為對const的引用總是將臨時對象的壽命擴展到其范圍。
boost::filesystem::recursive_directory_iterator it(dir_name);
const std::string& extension = it->path().extension().string();
std::cout << extension << std::endl; // error, dangling reference
從class path
的文檔中:
描述為返回
const string
成員函數被允許返回const string&
因此,不能保證string()
實際上會返回一個臨時字符串。 它可能是對extension()
返回的臨時path
內的字符串的引用; 不會有其壽命延長,因為它不直接結合到本地參考。
不要將extension
設為const ref。 改為這樣做:
const std::string extension = it->path().extension().string();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.