使用c ++中的typedef和模板的常量引用 [英] constant references with typedef and templates in c++

查看:211
本文介绍了使用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;
}

get的错误是无效的引用初始化

The error that is get is invalid initialization of reference of type 'int&' from expression of type 'const int'

推荐答案

类型的'int& p>

This:

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 你说的是make a type where T is immutable;因此在上一个例子中,指针(不是pointee)是不可变的。

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-qualifiers没有任何效果。

is meaningless, so adding cv-qualifiers to references has no effect.

因此,错误的类型为 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
}

到当函数返回时结束其生命周期的临时对象。也就是说,如果你使用它,你会得到未定义的行为,因为在refer和没有对象。这不比:

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和模板的常量引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆