const常引用
sshong 发表于2008年1月3日 20:10:00 更新于2008年1月3日 20:10:00
const 常引用与const reference生命周期延长

常引用
  使用const修饰符也可以说明引用,被说明的引用为常引用,该引用所引用的对象不能被更新。其定义格式如下:
  const <类型说明符> & <引用名>
  例如:
  const double & v;
  在实际应用中,常指针和常引用往往用来作函数的形参,这样的参数称为常参数。

#include <iostream>
using namespace std;
class A
{
public:
A(int i);
void print();
const int &r;
private:
const int a;
static const int b;
};
const int A::b=10;
A::A(int i):a(i), r(a)
{
}
void A::print()
{
cout<<a<<":"<<b<<":"<<r<<endl;}
void main()
{
A a1(100), a2(0);
a1.print();
a2.print();
}

  该程序的运行结果为:
  100:10:100
   0:10:0
  在该程序中,说明了如下三个常类型数据成员:
  const int & r;
  const int a;
  static const int b;
  其中,r是常int型引用,a是常int型变量,b是静态常int型变量。

按标准规定,临时对象可以被const  reference,这里临时对象的生命期将延长。而延长对象生命期的方法没有作规定,由编译器决定。
TC++PL中的描述:
A  temporary  created  to  hold  a  reference  initializer  persists  until  the  end  of  its  reference’s  scope.
注意到这里只是references  scope,所以当该引用出了定义的范围,该临时变量就析构了。这并不违反临时变量生存期的定义,它已经被视为const变量了。
/* For example*/
#include <iostream>
using namespace std;
int get(){
int n = 10;
return n;
}
int main(){
const int & n= get();
cout<<n<<endl;       // 10, fine。
return 0;
}
//No warnning,No error!
对于非const返回时候,是行不通的。


关于返回值转型为返回类型与析构临时变量的先后顺序,附:
//3.
//Call:        A c = returnA(1,1);
//Result:
//        A(int)
//        ~A()
//Reason:    本来与4一样的结果,但编译器进行了优化
//
A returnA(int,int)
...{
    return  A(300);
}
//4.
//Call:        A d = returnA(1,1,1);
//Result:
//        A(int)
//        A(A)
//        ~A()
//        ~A()
//Reason:   当d作用域完毕,析构函数
//
A returnA(int,int,int)
...{
    A a(400);    //构造函数A(int)
    return a;    //拷贝构造函数A(A),析构函数
}
标签:无分类:C++阅读:3688
评论
暂无评论
添加评论
您的大名,限长10汉字,20英文(*)
电子信箱(*)
您的网站
正文,限长500汉字,1000英文(*)
验证码(*) 单击刷新验证码
联系我
博客订阅