C++结构对齐与内联函数混用的时候要注意的

来源:互联网 发布:马鞍山淘宝店铺美工 编辑:程序博客网 时间:2024/05/21 09:08

/***************

*file1.h

***************/

//这里使用默认结构对齐,一般是8

class AAA

{

public:

      char    c;

      int       n;

public:

      void      Set(char s1, int s2);

public:

      int         Get() const { return n; }//内联函数

};

 

/***************

*file1.cpp

***************/

#include "stdafx.h"

#include "file1.h"

void AAA::Set(char s1, int s2)

{

       c = s1;

       n = s2;

}

 

 

 

/***************

*file2.h

***************/

#pragma pack(1) //注意这里使用1字节结构对齐

#include "file1.h"

class BBB

{

public:

      AAA       *     m_pA;

public:

      void      Fun();

};

 

/***************

*file2.cpp

***************/

#include "stdafx.h"

#include "file2.h"

void BBB::Fun()

{

       m_pA = new AAA;

       //这里的sizeof(*m_pA) == 5

       m_pA->Set( 1, 2);

       int nRet = m_pA->Get();

       //这里的nRet将不会等于2,因为这里内联函数展开相当于

       //int nRet = m_pA->n;

       //而因为这里1字节对齐,所以地址偏移只是1个字节

       //而实际上有AAA的构造函数的编译情况来看,是默认字节对齐的,也就是其成员变量C偏移0,而N变量时偏移了3个字节的

       //所以取值实际上应该是偏移3个字节的,nRet  = *(int*)((VOID*)m_pA + 4)

 

     

 

原创粉丝点击