Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
}
like image 436
sharyex Avatar asked Apr 15 '26 06:04

sharyex


1 Answers

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.

like image 172
StoryTeller - Unslander Monica Avatar answered Apr 16 '26 20:04

StoryTeller - Unslander Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!