2016-11-30 48 views
4

從我爲什麼理解,當你定義一個變量作爲一個函數返回值的引用時,你實際上有一個臨時對象的引用與生命週期綁定到引用和你必須將該參考文獻聲明爲const引用函數返回值和自動

這就是說,爲什麼不是臨時定義爲const這樣a2在下面的例子中會自動const
如果您不允許將非常量引用綁定到該臨時對象,那麼爲什麼不默認使臨時對象本身const?什麼是保持非常量的原因?

#include <string> 

std::string getStringA() 
{ 
    std::string myString = "SomeString"; 
    return myString; 
} 

const std::string getStringB() 
{ 
    std::string myString = "SomeString"; 
    return myString; 
} 


int main() 
{ 
    const std::string temp; 

    std::string &a1 = getStringA();  // std::string& a1, warning C4239 : nonstandard extension used : 'initializing' : conversion from 'std::string' to 'std::string &' 
    auto &a2 = getStringA();    // std::string& a2, warning C4239 : nonstandard extension used : 'initializing' : conversion from 'std::string' to 'std::string &' 
    const std::string &a3 = getStringA(); // all good 

    auto &b1 = getStringB();    // const std::string& b1 
    auto &b2 = temp;      // const std::string& b2 
} 
+0

您的'getStringA'示例僅適用於非標準的visual C++擴展。 – StoryTeller

+0

因此,爲了引用像'getStringA()'這樣的函數,你必須始終返回一個'const'?例如'getStringB()'。 – sharyex

+0

我建議永遠不要返回'const'值。看到我的答案。 – StoryTeller

回答

2

你不想返回const值,因爲它會kill move semantics

struct A { 
    A() = default; 
    A(A&&) = default; 
    A(A const&) = delete; 
}; 

A  foo() { return {}; } 
A const bar() { return {}; } 

int main() 
{ 
    A a1 {foo()}; 
    A a2 {bar()}; // error here 
} 

這是太多的代價的付出,只是爲了騰出自己綁定到一個臨時的打字auto const&的麻煩。