简体   繁体   中英

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). Eg: class A { int x; double y; int z; }; class A { int x; double y; int z; }; will use more memory than class A { double y; int x; int z; }; 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM