Chandu
Chandu

Reputation: 43

C++ memory Alignment on a 64 bit machine

Class A
{
  public:
    void fun1();
    void fun2();

  private:
     uint16 temp_var;
};

Is there any reason why I shouldn't just make this variable uint16 to full uint64? Doing it this way (uin16), do I leave memory "holes" in the object ?, and I'm told the processor is more efficient in dealing with full uint64s. for clarification, temp_var is the only member variable. And no where i was using it for size(temp_var) or as a counter to loop back to zero

Thank you all for your inputs, appreciate it..

Upvotes: 1

Views: 175

Answers (1)

TheUndeadFish
TheUndeadFish

Reputation: 8171

If the question is, can the compiler do the substitution:

You asked for a uint16 so it gave you a uint16. It would be surprising to get something else.

For instance, imagine if a developer was counting on a behavior of integer overflow or underflow. In that case, if the compiler substituted a uint64 behind the scenes, then that would be problematically surprising for the developer.

Along the same lines, one would expect sizeof(temp_var) to equal sizeof(uint16).

There are probably further cases in which such a substitution could lead to unexpected behavior that wouldn't be anticipated by the developer.


If the question is, can you the developer pick something else:

Sure, you can if you want a variable of that size. So then how about some possibilities where you wouldn't...

If you rely on overflow/underflow behavior of a uint16 then of course you would want to stick to that.

Or perhaps this data is going to be passed along to some further location that only supports values in the range of a uint16, so leaving it that size may make logical sense to try to implicitly document what's valid and/or avoid compiler warnings.

Similarly you might want for sizeof(temp_var) to be 2 bytes instead of 8 for some logical reason relevant to other parts of the program.

I also expect there are some games one could play with the packing pragma, but I presume that isn't relevant to the intended question.

Depending on the goal of your program, logical consistency or clarity of code may be more important than maximum possible performance (especially at the micro level of being concerned about size/type of a member variable). To phrase that another way, uint16 is still fast enough for many many use cases.

In some situations though, there won't be any compelling reason to make the decision one way or the other. At that point, I would go with whatever seems to make the most sense as per personal sensibilities.

Upvotes: 1

Related Questions