今天在看STL的RB-tree时,发现了一个很奇怪的赋值方式,形式如下:
root() = 0;
leftmost() = _M_header;
rightmost() = _M_header;
这三个函数原型为:
link _type& root() const { return (<link _type&) header->parent; }
link _type& leftmost() const { return (link _type&) header->parent; }
link _type&rightmost() const { return (link _type&) header->parent; }
类型标识符& 函数名()
用此形式时,相当于返回了一个变量,因为返回时返回的指针是指向变量的,因此,可以对它进行赋值操作,并且此处返回的变量,一般是全局变量或者静态变量,因此在函数返回时不会产生被返回值的副本。
下面用实例来说明一下:
#include<iostream>
using namespace std;
int num=0;
int& func()
{
return ++num; //此处num为全局变量
}
int main()
{
int i;
for(i=0;i<5;i++)
cout<<func()<<'\t';
cout<<endl;
func()=10;//对函数进行赋值,即将10赋给num
for(i=0;i<5;i++)
cout<<func()<<'\t';
cout<<endl;
}
输出为:
1 2 3 4 5
11 12 13 14 15
中间将10赋值给了函数func,因此,返回值num的值被改变为10了。同理,当返回值为静态变量时,测试代码如下:
#include<iostream>
using namespace std;
int& func()
{
static int num=0;
return ++num; //此处num为全局变量
}
int main()
{
int i;
for(i=0;i<5;i++)
cout<<func()<<'\t';
cout<<endl;
func()=10;//对函数进行赋值,即将10赋给num
for(i=0;i<5;i++)
cout<<func()<<'\t';
cout<<endl;
}
结果为:
1 2 3 4 5
11 12 13 14 15
注意:不能返回局部变量的引用。主要原因是局部变量会在函数返回后被销毁,因此被返回的引用就成为了"无所指"的引用,程序会进入未知状态。