Link to return function by value and auto

Due to what I understood, when you define a variable as a link to the return by value function, you really have a link to a temporary object with a lifetime bound to the link, and you must have this link declared as const.

As the saying goes, why is the temporary value not defined how const, so a2in the example below it will be automatic const?
If you are not allowed to bind a non-constant reference to this temporary object, why not make a temporary object by default const? What is the reason to keep it non-constant?

#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
}
+4
source share
1

const, .

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& .

+2

Source: https://habr.com/ru/post/1662405/


All Articles