vendredi 27 avril 2018

C++ decltype(auto) of const reference return type [duplicate]

This question already has an answer here:

This is the test program I have:

#include <iostream>
#include <typeinfo>
using namespace std;

template <typename T>
decltype(auto) foo(T& arg)
{
    return arg;
}

int main()
{
    const int x = 10;
    int & y = const_cast<int&>(foo(x));
    y = 20;
    cout << "x: " << &x << " " << x << endl;
    cout << "y: " << &y << " " << y << endl;
}

Output:

g++ -std=c++17 main.cpp  && ./a.out
x: 0x7ffee31f4a6c 10
y: 0x7ffee31f4a6c 20

Why was the value of x not changed even though foo returned a const int& to which it was const_cast'ed to int&?

Because from the output it seems like the two addresses of x and y are the same.

Aucun commentaire:

Enregistrer un commentaire