不同gcc版本的结构成员

时间:2015-07-24 04:54:28

标签: c++ templates memory-alignment pack

#include <iostream>
#include <stdint.h>

#pragma pack(1)
struct Foo
{
    uint8_t f1;
    uint8_t f2;
    uint32_t f3;
};

struct Bar
{
    uint64_t b1;
    Foo b2;
    bool b3;
};

template<typename BT1, typename BT2, bool BT3= false>
class BarTemplate
{
public:
    BT1 bt1;
    BT2 bt2;
    bool bt3;
};
#pragma pack()

int main(int argc, const char* argv[])
{
    std::cout << "compile ver: " << __VERSION__ << std::endl;
    std::cout << "sizeof Foo: " << sizeof(Foo) << std::endl;
    typedef BarTemplate<uint64_t, Foo> BarT;
    std::cout << "sizeof BarTemplate<uint64_t, Foo>: " << sizeof(BarT) << std::endl;
    std::cout << "sizeof Bar: " << sizeof(Bar) << std::endl;

    return 0;
}

此代码在gcc 4.4.6和gcc 4.8中有diff输出。

编译版本:4.4.6 20120305(Red Hat 4.4.6-4) sizeof Foo:6 barTemplate的大小:16 酒吧:15

编译版本:4.8.2 sizeof Foo:6 barTemplate:15 酒吧:15

gcc 4.4和4.8与模板中的包成员有什么区别?

2 个答案:

答案 0 :(得分:0)

我认为那是因为gcc Memory Alignment,编译器期望内存分配大小是4字节的整数倍数。 但gcc 4.8不这样做。

答案 1 :(得分:0)

不同版本的gcc编译器explent pragma pack()来实现不同的代码 我的gcc 4.4.7代码是这样的:

#include <iostream>
#include <stdint.h>

#pragma pack(1)
struct Foo
{
   uint8_t f1;
   uint8_t f2;
   uint32_t f3;
};

struct Bar
{
  uint64_t b1;
  Foo b2;
  bool b3;
 };
 #pragma pack(1)

 template<typename BT1, typename BT2, bool BT3= false>
 class BarTemplate
 {
   public:
   BT1 bt1;
   BT2 bt2;
   bool bt3;
 };

 int main(int argc, const char* argv[])
 {
     std::cout << "compile ver: " << __VERSION__ << std::endl;
     std::cout << "sizeof Foo: " << sizeof(Foo) << std::endl;
     typedef BarTemplate<uint64_t, Foo> BarT;
     std::cout << "sizeof BarTemplate<uint64_t, Foo>: " << sizeof(BarT) <<           std::endl;
     std::cout << "sizeof Bar: " << sizeof(Bar) << std::endl;

     return 0;
 }

结果:

compile ver: 4.4.7 20120313 (Red Hat 4.4.7-11)
sizeof Foo: 6
sizeof BarTemplate<uint64_t, Foo>: 15
sizeof Bar: 15