Mel*_*ael 15 c++ templates const reference temporary
我听说临时对象只能分配给常量引用.
但是这段代码给出了错误
#include <iostream.h>
template<class t>
t const& check(){
return t(); //return a temporary object
}
int main(int argc, char** argv){
const int &resCheck = check<int>(); /* fine */
typedef int& ref;
const ref error = check<int>(); / *error */
return 0;
}
Run Code Online (Sandbox Code Playgroud)
得到的错误是 invalid initialization of reference of type 'int&' from expression of type 'const int'
GMa*_*ckG 20
这个:
typedef int& ref;
const ref error;
Run Code Online (Sandbox Code Playgroud)
不做你认为它做的事.请考虑一下:
typedef int* pointer;
typedef const pointer const_pointer;
Run Code Online (Sandbox Code Playgroud)
类型const_pointer
是int* const
,而不是 const int *
.也就是说,当你说const T
你说"做一个T不可变的类型"时; 所以在前面的例子中,指针(不是指针对象)是不可变的.
无法参考const
或volatile
.这个:
int& const x;
Run Code Online (Sandbox Code Playgroud)
没有意义,所以在引用中添加cv限定符没有任何效果.
因此,error
有类型int&
.你不能指定const int&
它.
您的代码中还有其他问题.例如,这当然是错误的:
template<class t>
t const& check()
{
return t(); //return a temporary object
}
Run Code Online (Sandbox Code Playgroud)
你在这里做的是返回一个临时对象的引用,它在函数返回时结束它的生命周期.也就是说,如果使用它,则会得到未定义的行为,因为在参考文件中没有对象.这并不比:
template<class t>
t const& check()
{
T x = T();
return x; // return a local...bang you're dead
}
Run Code Online (Sandbox Code Playgroud)
更好的测试是:
template<class T>
T check()
{
return T();
}
Run Code Online (Sandbox Code Playgroud)
函数的返回值是临时的,因此您仍然可以测试您确实可以将临时值绑定到常量引用.
由于英语语法的运作方式,这对于说英语的人来说是一个非常常见的错误.
我认为非常不幸的是C++语法允许两者:
const int // immutable int
int const // immutable int
Run Code Online (Sandbox Code Playgroud)
具有相同的含义.
它不会使它更容易,真的,并且不可组合,因为:
const int* // mutable pointer to immutable int
int* const // immutable pointer to mutable int
Run Code Online (Sandbox Code Playgroud)
当然不具有相同的含义.
不幸的是,对于你来说,正如@GMan所解释的那样.
如果你希望将来避免这种错误,请养成在你的权利上对你的类型(const
和volatile
)进行限定的习惯,然后你就可以将一个简单的文本替换.typedef
您的代码会出错,因为const
限定符const ref error
只是被忽略,因为它8.3.2/1
说
除非通过使用typedef(7.1.3)或模板类型参数(14.3)引入cv限定符,否则Cv限定引用的格式不正确,在这种情况下,cv限定符将被忽略.
所以error
有类型int&
没有const int&
.