C++'s pshpack & poppack & array padding

Started by
6 comments, last by Atash 17 years, 2 months ago
I've read around and found that C may or may not pad an array of structs to take advantage of the word length on a particular machine. I've also read that pshpack and poppack can overload the automatic type padding, and I'm wondering if this would be the correct usage of the terms to avoid type padding:
[source lang=cpp]
#include <pshpack1.h>
template<typename T, unsigned int N>
class Array
{
protected:
	T elems[N];
public:
	// member access
	operator const T* () const /*----*/ { return elems; }
    operator T* () /*----------------*/ { return elems; }
    T operator[] (int i) const /*----*/ { return elems; }
    T& operator[] (int i) /*---------*/ { return elems; }
};
#include <poppack.h>

*After Argument*P1: What was it about?P2: Something involving a chair, a cat, and a rubber ducky...
Advertisement
Padding is a compiler specific thing, not a part of the language.
"I thought what I'd do was, I'd pretend I was one of those deaf-mutes." - the Laughing Man
Well, it isn't part of the language, yes, but I'm wondering if including pshpack.h and poppack.h would stop automatic byte-alignment...
*After Argument*P1: What was it about?P2: Something involving a chair, a cat, and a rubber ducky...
It looks ok to me, but I'm more of a straight C programmer so I don't know how the packing impacts on the template. My comment was more germain to the title of the thread.
"I thought what I'd do was, I'd pretend I was one of those deaf-mutes." - the Laughing Man
Ah. Okay :) Thanks.
*After Argument*P1: What was it about?P2: Something involving a chair, a cat, and a rubber ducky...
The distance between two consecutive elements in an array of T is sizeof(T). There is never any padding between array elements: all padding is part of T, and thus represented in sizeof(T). If you want to reduce the size of an array of T, your only possibility is to reduce the size of T itself.
So from what ToohrVyk said, wrapping the template definition in pragma packs won't make a difference. The packing needs to be applied to whatever T is.

"I thought what I'd do was, I'd pretend I was one of those deaf-mutes." - the Laughing Man
Aye. Thank you!
*After Argument*P1: What was it about?P2: Something involving a chair, a cat, and a rubber ducky...

This topic is closed to new replies.

Advertisement