C++ C++;常量引用返回类型的decltype(auto)
这是我的测试程序:C++ C++;常量引用返回类型的decltype(auto),c++,c++11,c++17,C++,C++11,C++17,这是我的测试程序: #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)
#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;
}
为什么即使foo
返回了一个const-int&
,但x
的值没有改变,它被const-u-cast
转换为int&
因为从输出来看,似乎x
和y
的两个地址相同。也可能重复:
g++ -std=c++17 main.cpp && ./a.out
x: 0x7ffee31f4a6c 10
y: 0x7ffee31f4a6c 20