Search code examples
c++c++11c++20auto

Using auto to a variable assigned ot a function that return const ref


const className& f();

If I have a function that return const ref. And use it's value to assign to a variable using auto

auto v1 = f();
auto& v2 = f();
const auto& v3 = f();
decltype(auto) v4 = f();

As far as I understand all those three option will be same. But should I still prefer to write like for v3 to be explicit in my code that it's const ref? Or maybe in C++14/C++17/C++20 now there is some other preferrable way?

Or am I wrong and they are actually different? UPDATE: so seems I was wrong. And only decltype(auto) and const auto& will make variable const ref?


Solution

  • If I have a function that return const ref. And use it's value to assign to a variable using auto

    I believe you meant to initialize the variables with the function f:

    auto        v1 = f();
    auto&       v2 = f();
    const auto& v3 = f();
    

    As far as I understand all those three option will be same.

    No, they are not the same

    static_assert(std::is_same_v<decltype(v1), className>);
    // plain auto does not deduce reference or apply const
    static_assert(std::is_same_v<decltype(v2), const className&>);
    // v2 will also be const& as function returns const&
    static_assert(std::is_same_v<decltype(v3), const className&>);