开发者

Preserving specified primitive size

If I have a class as follows:

class MyData
{
public:
    MyData( const AnotherObject& obj );

    int getA() { return A; }
    int getB() { return B; }

private:
    int A : 16;
    int B : 16;
}

Will the fact that I have specified the variables A and B to take up only 16 bits be rendered pointless by the getters? If I pass an instance of this class around, and other objects want access to A and B but I want to preserve the sizing that I have specified, will I lose开发者_运维技巧 that because getA() and getB() will return 32-bit copies?

Would I be better off making A and B public and accessing them directly as required? Will this preserve the sizing? Or should I return references to them from the getters?


The getters will convert the 16 bit value to the size of the int on the system value and will return 32-bit copies (if the size is 32 bits).

What is it that you're trying to achieve? Why not use int16_t from <cstdint>?


The return types of getA and getB have no effect on the layout of the class. So your code should work as you want it to.


In most C++ implementation adding non-virtual methods doesn't change the size or memory layout of a class instance. The class memory layout will most probably change instead when you add virtual methods or inheritance.

Note of course that the exact memory layout is implementation dependent and this means that it may change depending on compiler vendor, compiler version and even compiler options.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜