Pointers to Incomplete Types
Consider the following:
class Incomplete;
class Complete
{
Incomplete* Foo; // Will only compile if Foo is a pointer.
};
class Incomplete
{开发者_如何学运维
Complete Bar; // Bar can be a pointer or an object.
};
How are pointers to incomplete types legal? How does the compiler know how big an object of type Incomplete
is? And since it can apparently figure out the size, why are regular objects of incomplete types illegal?
The reason that pointers to incomplete types are legal is precisely because the compiler doesn't need to know their size.
The reason that you cannot declare an object of incomplete type is, as you've mentioned, because the compiler doesn't know how large the object is and therefore can't allocate space for it. When declaring a pointer to an incomplete type, though, the size is known because typically all pointers on a machine have the same size.
Moreover, you don't need to know how large the object is when declaring a pointer to an object of incomplete type. However, if you try using an object of incomplete type, such as by following that pointer or trying to instantiate an object of that type, then the compiler will give you an error.
In short, the pointer is legal because it can be created without the compiler knowing the size of what's being pointed at. If you actually need to know the size or layout of that object by using the pointer, though, the compiler will need to have more information about the type.
The size of a pointer is not dependent on the size of the type it points to. int*
and Incomplete*
are of the same size.
For regular objects, however, the size is unknown.
The compiler doesn't need to know how big instance of Incomplete
is, because pointers are always the same size.
How does the compiler know how big an object of type Incomplete is?
It doesn't. It works with a pointer because the compiler knows the size to allocate for the pointer.
精彩评论