简体   繁体   中英

Reference to function return by value and auto

From why I understood, when you define a variable as a reference to a function return by value you actually have a reference to a temporary object with a lifetime that is bound to the reference and you must have that reference declared as const .

That being said, why isn't the temporary defined as a const such that a2 in the example below would be automatically const ?
If you aren't allowed to bind a non-const reference to that temporary object, then why not make the temporary object itself const by default? What's the reason to keep it non-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
}

You don't want to return a const value, because it will 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
}

And that is too much of a price to pay, just to spare yourself the hassle of typing auto const& for binding to a temporary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM