在這種情況下會發生什麼?將一個右值賦給'const auto'時會發生什麼
// assume WeakPtr is valid and has not expired
const auto& something = WeakPtr.lock();
something->doStuff();
這是undefined?
它在這種情況下會改變嗎?
std::shared_ptr<Something> getSomething() { return mSomething.lock(); }
const auto& something = getSomething();
這又怎麼樣?
std::vector<int> getInts() { return std::vector<int>{ 1, 2, 3 }; }
const auto& ints = getInts();
在每種情況下const auto&
意味着我要綁定到的對象的引用,但在每一種情況下,我將它綁定到一個臨時右值對象。我是否在邀請災難?
整潔如何問題像這樣聚集起來:http://stackoverflow.com/questions/42868517/why-can-you-intialize-a-const-reference-but-not-a-non-const-reference -from-an-rv一些有用的評論關於什麼和什麼因素。 – user4581301
重要的是要注意「臨時」和「右值」之間的區別。後者是嚴格更一般的。例如,比較'const int&r = 5;'和'const int&q = std :: move(5);'。兩者都是rvalues,一個是災難。 –