問題描述
我聽說臨時對象只能分配給常量引用.
I heard the temporary objects can only be assigned to constant references.
但是這段代碼報錯
#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;
}
得到的錯誤是類型'int&'的引用初始化無效from 'const int' 類型的表達式
推薦答案
這個:
typedef int& ref;
const ref error;
沒有做你認為它會做的事情.考慮一下:
Doesn't do what you think it does. Consider instead:
typedef int* pointer;
typedef const pointer const_pointer;
const_pointer
的類型是int* const
,不是 const int *
.也就是說,當您說 const T
時,您是在說創建一個類型,其中 T 是不可變的";所以在前面的例子中,指針(不是被指點者)是不可變的.
The type of const_pointer
is int* const
, not const int *
. That is, when you say const T
you're saying "make a type where T is immutable"; so in the previous example, the pointer (not the pointee) is made immutable.
引用不能是const
或volatile
.這:
int& const x;
沒有意義,因此向引用添加 cv 限定符沒有任何效果.
is meaningless, so adding cv-qualifiers to references has no effect.
因此,error
的類型為 int&
.您不能為其分配 const int&
.
Therefore, error
has the type int&
. You cannot assign a const int&
to it.
您的代碼中存在其他問題.例如,這肯定是錯誤的:
There are other problems in your code. For example, this is certainly wrong:
template<class t>
t const& check()
{
return t(); //return a temporary object
}
您在這里所做的是返回對臨時對象的引用當函數返回時該對象結束其生命周期.也就是說,如果你使用它,你會得到未定義的行為,因為在引用處沒有對象.這并不比:
What you're doing here is returning a reference to a temporary object which ends its lifetime when the function returns. That is, you get undefined behavior if you use it because there is no object at the referand. This is no better than:
template<class t>
t const& check()
{
T x = T();
return x; // return a local...bang you're dead
}
更好的測試是:
template<class T>
T check()
{
return T();
}
函數的返回值是臨時的,所以你仍然可以測試你確實可以將臨時對象綁定到常量引用.
The return value of the function is a temporary, so you can still test that you can indeed bind temporaries to constant references.
這篇關于C++ 中帶有 typedef 和模板的常量引用的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!