常量引用 const T&

 

1.引用本身不是对象,只是引用对象的别名,没有内存空间产生

2.引用必须严格类型匹配

3.而常量引用 const T& 可以引用字面值常量及表达式 其实也就是右值,且常量引用的不同与T类型对象时,如果可以类型转换则会类型转换为T类型常量引用,不过会产生临时变量(C++ Primer):  

code:

double d=25.0;

const int& a=d;

implicit code:

double d=25.0;

const int temp=d;

const int& a=temp;

 

所以常量引用时如果出现自动类型转换就要得注意临时变量作用域了,以下是衍生到模板显示调用时可能出现的问题

#include <iostream>
#include <string>


template <typename T>
inline const T&  max(const T& a,const T& b)
{
    return a>b? a:b;
}



int
main()
{
    //类型转换都会产生临时变量
    //const T& 类型不同需要转换时 引用的是临时变量
    //模板指定显示参数类型时注意如果类型不同引用的可能是临时变量
    double a=20.2,b=30.2;
    const double& c=max(a,b);
    std::cout<<c<<std::endl;
    b=200;
    std::cout<<c<<std::endl;

    a=20.2;
    b=30.2;
    const int& d=max<int>(a,b);
    std::cout<<d<<std::endl;
    b=200;
    std::cout<<d<<std::endl;
    
//    编译器:clang
//    out:
    
//    30.2
//    200
//    30
//    30


    return 0;
}

 

转载于:https://www.cnblogs.com/xuaidongstdudyrecording/p/9501260.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值