2016-11-30 47 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&的麻烦。