const&
在這種情況下不會延長壽命。考慮構建一個臨時的example here,然後嘗試打印它:它使用與您的代碼相同的構造,但我已經修改它以使對象構造和銷燬對用戶更加明確。
#include <iostream>
struct reporting {
reporting() { std::cout << "Constructed" << std::endl;}
~reporting() { std::cout << "Destructed" << std::endl;}
reporting(reporting const&) { std::cout << "Copy-Constructed" << std::endl;}
reporting(reporting &&) { std::cout << "Move-Constructed" << std::endl;}
reporting & operator=(reporting const&) { std::cout << "Copy-Assigned" << std::endl; return *this;}
reporting & operator=(reporting &&) { std::cout << "Move-Assigned" << std::endl; return *this;}
void print() const {std::cout << "Printing." << std::endl;}
};
const reporting& get_or(const reporting& def)
{
return def;
}
int main()
{
const reporting& foo = get_or(reporting{});
foo.print();
return 0;
}
輸出:
Constructed
Destructed
printing.
注意如何顯示printing.
前的物體被破壞。
您可能想知道爲什麼代碼仍然完成,沒有可見的錯誤:這是未定義行爲的結果。有問題的對象不存在,但因爲它不依賴於狀態來調用它的方法,程序恰好不會崩潰。其他更復雜的例子不能保證這個功能不會崩潰或導致其他意想不到的行爲。
順便說一句,事情有點不同,如果臨時爲bound directly to the const&
:
#include <iostream>
struct reporting {
reporting() { std::cout << "Constructed" << std::endl;}
~reporting() { std::cout << "Destructed" << std::endl;}
reporting(reporting const&) { std::cout << "Copy-Constructed" << std::endl;}
reporting(reporting &&) { std::cout << "Move-Constructed" << std::endl;}
reporting & operator=(reporting const&) { std::cout << "Copy-Assigned" << std::endl; return *this;}
reporting & operator=(reporting &&) { std::cout << "Move-Assigned" << std::endl; return *this;}
void print() const {std::cout << "printing." << std::endl;}
};
const reporting& get_or(const reporting& def)
{
return def;
}
int main()
{
const reporting& foo = reporting{};
foo.print();
return 0;
}
輸出:
Constructed
printing.
Destructed
看到物體是如何不被破壞,直到用完之後。在這種情況下,對象會一直存在直到範圍結束。
接受的答案到你引用的問題(引用標準)明確說明了兩種情況,這是行不通的。你的例子是第二種情況:在函數調用中臨時綁定到引用參數。所以答案是否定的。 –