当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - How to order members of a class if there are static members too?

问题描述:

I know that order in declaration of the members of a class matters for using less memory (descending order based on type size). E.g.: class A { int x; double y; int z; }; will use more memory than class A { double y; int x; int z; };

Is this still true for the latest compilators (I use Ubuntu)? If yes, where shall I put the static members?

class A

{

private:

static int m1;

double m2;

int m3;

public:

// ...

};

Where shall I place m1 in this place for using less memory?

网友答案:

According to the C++ Standard

A static data member is not part of the subobjects of a class.

So they may have even incomplete types in the class definition. They do not influence on the size of a class.

网友答案:

Static data members are not stored in the class instances; instead you get one instance of each one, and these "live" in the place where you defined them.

struct A
{
  static int m1;
  double m2;
  int m3;
};

int A::m1; // <--- this lives here!

As such, the position of their declaration within the definition of A is entirely immaterial for the padding, alignment and ordering of A's non-static data members.

分享给朋友:
您可能感兴趣的文章:
随机阅读: