问题
The short version of this question: Does a pointer to the first data member of a class result in a pointer to all its data members?
Discussion:
I'm reading some sample code, and this is interesting. When a particular function (in this case the glUniformMatrix4fv
C function from OpenGL) takes as a parameter an array, this is passed in the common C way of using a pointer to the address of the array's first element, as follows:
glUniformMatrix4fv(glvariable, 1, 0, &newmatrix[0]);
// referring to newmatrix
This developer has a C++ class for creating a 4X4 matrix, for a total of 16 floats. However, the data members of that class are divided into 4 separate vectors of 4 data members each:
Here are the data members of the class:
vec4 x;
vec4 y;
vec4 z;
vec4 w;
The vec4
class in turn provides these data members:
T x;
T y;
T z;
T w;
He then creates a function to point to just the first vec4 x
data member:
const T* Pointer() const
{
return &x.x;
}
And somehow, this miraculously translates into sending all 4 vec4
objects and their respective 4 components:
glUniformMatrix4fv(modelviewUniform, 1, 0, modelviewMatrix.Pointer());
I'm fairly new to C++ but this surprised me that you can point to just one data member and expect all the rest to get sent as well. Is it because the class defines them in a particular order? What if they had been defined in a different order in the class definition?
回答1:
This is the C++ object model. You're guaranteed that within the same access level (private
/public
/protected
), the object properties are in order (C++11), and the same for members without access specifiers between them (in C++03).
This doesn't mean what you're doing is a good idea. It's better to avoid the cast and just have the function do some more work.
C++11:
9.2 Class members [class.mem]
14) Nonstatic data members of a (non-union) class with the same access control (Clause 11) are allocated so that later members have higher addresses within a class object. The order of allocation of non-static data members with different access control is unspecified (11). Implementation alignment requirements might cause two adjacent members not to be allocated immediately after each other; so might requirements for space for managing virtual functions (10.3) and virtual base classes (10.1).
C++03
9.2 Class members [class.mem]
12) Nonstatic data members of a (non-union) class declared without an intervening access-specifier are allocated so that later members have higher addresses within a class object. The order of allocation of non-static data members separated by an access-specifier is unspecified (11.1). Implementation alignment requirements might cause two adjacent members not to be allocated immediately after each other; so might requirements for space for managing virtual functions (10.3) and virtual base classes (10.1).
来源:https://stackoverflow.com/questions/14352373/classes-store-data-members-in-sequential-memory