Hello,
I've read somewhere that std::allocator works by allocating a block of memory that is large enough to hold an object, then it constructs an object from it.
I decided to go look at my compiler's (MSVC) definition of std::allocator, but I'm sure you guys have seen how readable it is (:P).
I don't know how it constructs an object that is derived from a base class since the vtable takes up space which I can't seem to figure out through the program. (A great example would be to try to call something likeDerived* derived = malloc(sizeof(Derived)); then try to use it, you'll see what I mean).
So how does the standard allocator determine how large a derived object is?
By using new, as far as I can tell. The reference on this site also suggests that:
In the standard default allocator, the block of storage is allocated using ::operator new one or more times, and throws bad_alloc if it cannot allocate the total amount of storage requested.
EDIT:
Here is an example allocate function: T* allocate (std::size_t n) { returnstatic_cast<T*>(::new(n*sizeof(T))); }
Yes, there is - that is what the example is doing. The 'T' is the derived class, it retrieves the size of 'T' and allocates a block of 'n' times that. Think about it - you can't do Derived* derived = new Base;, can you? This does Derived* derived = new Derived;, and it just so happens that Derived* can be implicitly converted to Base*, which is probably where you are getting your confusion from.
Basically, you can get the size of the object that is derived from the base class, but not from a pointer or reference to the base class - you'd have to cast it to the derived class first (preferably using dynamic_cast).