sizeof 注意事项

sizeof关键字的作用很简单, 就是获取一个类型的大小. 下面看一下C++使用sizeof获取类大小的情况.

  • 空类的大小为1:
  class empty{};
  int main(void) {
      std::cout << sizeof(empty) << std::endl; // 1
  }

与C不同的是, C中空结构体的大小为0.

  • 类中静态成员和非虚函数不会占用类大小:
  class empty {
      public:
          static int m_a;

      public:
          void show(void) {
              std::cout << m_a << std::endl;
          }
  };

  int main(void) {
      std::cout << sizeof(empty) << std::endl; // 1
  }
  • 一个或多个虚函数都保存到vptr中, 故占用一个指针大小:
  class empty {
      public:
          static int m_a;

      public:
          virtual void show(void) {
              std::cout << m_a << std::endl;
          }

          virtual void set(int a) {
              m_a = a;
          }
  };

  int main(void) {
      std::cout << sizeof(empty) << std::endl; // 8
  }
  • 子类大小 = 父类大小 + 子类成员大小(不包括虚函数表vptr的大小):
  class base {
      private:
          int m_a;
  };

  class derive: public base {
      public:
          int m_a;
  };

  int main(void) {
      std::cout << sizeof(base) << std::endl; // 4
      std::cout << sizeof(derive) << std::endl; // 8
  }
  • 虚继承的子类大小 = 各个父类大小的和:
  class base_1 {
    private:
      virtual void show();
  };

  class base_2 {
    private:
      virtual void show();
  };

  class derive : virtual public base_1, virtual public base_2 {
    public:
      void show();
  };

  int main(void) {
      std::cout << sizeof(base_1) << std::endl; // 8
      std::cout << sizeof(base_2) << std::endl; // 8
      std::cout << sizeof(derive) << std::endl; // 16
  • 虚函数和普通多继承: 子类大小 = 父类大小 + 子类成员大小(不包括虚函数表 vptr的大小)
  class base_1 {
    public:
      virtual void show() { std::cout << "base_1" << std::endl; };
  };

  class base_2 {
    public:
      virtual void show() { std::cout << "base_2" << std::endl; };
  };

  class base_3 {
    public:
      virtual void show() { std::cout << "base_3" << std::endl; };
  };

  class derive : public base_1, public base_2, public base_3 {
    public:
      virtual void show() { std::cout << "derive" << std::endl; };
  };

  int main(void) {
      std::cout << sizeof(base_1) << std::endl; // 8
      std::cout << sizeof(base_2) << std::endl; // 8
      std::cout << sizeof(base_3) << std::endl; // 8
      std::cout << sizeof(derive) << std::endl; // 24
  }

如果觉得有帮助,可以扫描右边的微信打赏码支持一下.

Leave a Reply

Your email address will not be published. Required fields are marked *