A C++ object with virtual methods and some members looks like this, if you put it in terms of C:
struct ClassVTable {
void (*firstMethod)();
void (*secondMethod)();
}
struct Class {
struct ClassVTable *virt;
int firstMember;
int secondMember;
};
and a pointer to it looks like: struct Class *objectRef;
A language that uses fat pointers, like rust, has this separated completely: struct Class {
int firstMember;
int secondMember;
};
struct FatPointerToClass {
struct ClassVTable *virt;
struct Class *data;
}
FatPointerToClass objectRef; // note lack of pointer, it'd be stored on the stack directly for eg.
This means a much simpler object layout in exchange for passing around larger pointers, and it's a good fit for trait-based typing since it doesn't require you to know all possible interface subtypes of the object in order to describe or use its layout.(please note that I'm using C struct to be precise about the concept, and this should not be taken as a perfectly verbatim description of the actual object layouts in memory)
Re:Announcing Rust 1.27
by Coding_Cat on Thursday June 21, 2018 @08:42PM
(#17370372)
Oh, I didn't know that: this is also great for serializing code where you might have an array of `Class`, it would still be a POD-type to use C++ language.
Re:Announcing Rust 1.27
by steveklabnik on Thursday June 21, 2018 @07:33PM
(#17370073)
My understanding is that, generally (because (again in my understanding) this is all compiler-specific, not mandated by the standard) is that in C++, there's a single pointer that points to the combo of the vtable and then the data, after it. See http://www.drdobbs.com/cpp/storage-layout-of-polymorphic-obj... for example. While a Shape is a position, outline, and fill, if you have virtual functions, the pointer points to a vtable pointer, and then all of the data.
In other words, in Rust, a pointer to a shape is
(pointer to vtable, pointer to data)
whereas, in C++, a pointer to a shape is (pointer to shape)
where shape is (pointer to vtable, data)
If that's incorrect, I'm quite happy to be corrected! This isn't an area I'm an expert in.That’s absolutely correct.
I get it now, that you meant the “pointer to the vtable” under “vtable” in your original post.
Re:Announcing Rust 1.27
by steveklabnik on Friday June 22, 2018 @06:49AM
(#17372974)
Ah, I see. Yes, I should probably have been more clear there. Thanks for pointing that out.
Which “data” is the vtable stored with in C++? An object contains only a pointer to its vtable, not the vtable itself...