constant references with typedef and templates in c++(c++ 中 typedef 和模板的常量引用)
问题描述
听说临时对象只能分配给常量引用.
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&' 类型的引用初始化无效来自 '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
,not 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
.这个:
References cannot be made const
or volatile
. This:
int& const x;
没有意义,所以在引用中添加 cv-qualifiers 没有任何效果.
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 和模板的常量引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:c++ 中 typedef 和模板的常量引用
基础教程推荐
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- 运算符重载的基本规则和习语是什么? 2022-10-31
- C++,'if' 表达式中的变量声明 2021-01-01
- 设计字符串本地化的最佳方法 2022-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01