您的位置:首页 > 编程语言 > C语言/C++

c++ 转型为 引用类型 的作用

2014-08-23 21:10 309 查看
情景:近来看到

1.《深入浅出MFC》中p128 有如此语句:

ar >> (WORD&) m_center.x;

ar >> (WORD&) m_center.y;

ar >> (WORD&) m_radius;

之前也知道这几句无非就是提取数据放到这里面,但没有弄清为什么要加一个 & 符号,都是囫囵吞枣,照猫画虎的学着做。。

2. 还有, 微软预定义的 #define _ADDRESSOF(v) ( &reinterpret_cast<const char &>(v) )。

test

#include "stdafx.h"
#include<iostream>
using namespace std;

class Int
{
public:
int a;

Int(int _a) : a(_a)
{
cout << "                Construct Int... " << endl;
}
};

class TwoInt
{
public:
int b;
int c;

TwoInt(int _b, int _c) : b(_b), c(_c)
{
cout << "Construct  TwoInt.. " << endl;
}
};

// 注意看 cin 对象的 >>,
// 在istrem文件中如此定放 _Myt& __CLR_OR_THIS_CALL operator>>(unsigned short& _Val){...} 的定义就知了
void testFunc(Int& i)
{
cout << "testFunc()  : " << i.a << endl;

i.a = 5000;
}

// 测试下内置类型时的情况
void test(int& i)
{
i = 845556;
}

int main()
{
TwoInt testVar(12, 99);

#if 1
testFunc((Int&)testVar.b); // 注意看这两句打印出的信息,或是反汇编出来观察
#else
testFunc((Int)testVar.b);
#endif

cout << testVar.b << endl; // 也注意观察这句对应于上面两种情况转出的变化。

// 以下内容测试下内置类型的情况
cout << "==============================" << endl;

// 注意看这里 VS2010 反汇编出来是一样的

test((int&)testVar.b);
//010815F1  mov         eax,dword ptr [testVar]
//010815F4  push        eax
//010815F5  call        test (1081262h)
//010815FA  add         esp,4

test(testVar.b);
//010815FD  mov         eax,dword ptr [testVar]
//01081600  push        eax
//01081601  call        test (1081262h)
//01081606  add         esp,4

cout << testVar.b << endl;
}


结论:对于非内置类型的,如果不加上& 的话,会因为转型而产生临时对象。

对于内置类型的,则是一样。。

ps. vs2010 编译器对于好些产生临时对象的,已经优化的不错了。。

ps. 纯好奇之作, 屠龙之技也,不足一看..
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: