On Jul 15, 6:27 am, ?? Tiib <oot...@hot.ee> wrote:
Memory representation does not matter to non-POD types, because you
may not rely on it, cast to char* and memcpy between them. If you
have valid pointer of type foo* in source code then you know
nothing that really happens. Is foo most derived type of the
object pointed at? Is foo array element? In what type of storage
it is? So you may not assume anything, but implementation may have
clever ways to find it out and make difference and to optimize
there things. It goes worse and worse when there is virtual
inheritance or reference data member or the like in foo.
Some think that it is something theoretical and far. Nope. It is
present in practice. For example people writing debugger for
specific implementation on specific platform have to rely on
memory layout of stuff to display it to user. Everybody have seen
how confused are debuggers with optimized code and data sometimes.
Not overly complex code and data even. The devs of debugger did
have docs for all implementation-specific internals. However they
have difficulties. Now ... if they do not manage then ... nothing
to talk of "portable" bla-bla "way" here. For managing binary
representation there are POD types and that is it.
To reiterate my question, I don't understand how an object could
exist in non-contiguous storage, but still be creatable with
placement new. Ex:
char * c = new char[sizeof(foo)]
foo * f = new (c) foo();
We know that there is a foo object in the storage of c[0] to
c[sizeof(foo)-1], inclusive. We know that all bytes in that storage
are occupied by the foo object. Some may be padding, some may not be
padding. However, the foo object
- exists in that storage,
- exists only that storage and no where else,
- and exists in all of that storage so that none of the storage is
usable for another purpose while the foo object is usable.
As I said earlier, if you dynamically allocate such a non-POD object
with regular new, it could do weird things behind your back, but
objects allocated via placement new still must exist in a contiguous
block of memory, and I would think any implementation is silly which
allocates objects differently with regular new and placement new.
But there is no rule against silly implementations. :-)
If you want to be portable to the most common implementations, fine.
avoid all the tricky stuff.