Subject: Re: [ub] type punning through congruent base class?
From: Ion Gaztañaga (igaztanaga_at_[hidden])
Date: 2014-01-16 16:34:23
El 16/01/2014 22:10, Herb Sutter wrote:
> And dare I ask: Um, what about using part of the same allocated
> buffer to hold a T and another part to hold a U, such as malloc(1000)
> and read/write an int at offset 10 and read/write a short at offset
> 314 -- they're the same allocation, so do we even have any way to
> talk about that?
Any existing memory allocator use this pattern (obtaining memory via
mmap/VirtualAlloc and buffers and writing metadata for management
purposes and splitting and coalescing chunks of memory writing new
metadata, all whithout calling any constructor and destructor).
We are missing a mechanism to support system programming techniques that
reuse storage, even for objects that have a constructors, just like we
support not explicitly calling the destructor in 3.8 [basic.life] p.4
"the program is not required to call the destructor explicitly before
the storage which the object occupies is reused or released".
Imagine we have a mechanism for that:
//Assume "storage" is properly aligned
//and big enough to store an object
//of type T
void* storage = malloc(...);
void *storage = &one_object_of_type_X;
void *storage = &array_of_type_Y[array_size/2];
//The lifetime of the object (if any)
//stored (even partially) in "storage" ends in the
//following line. The storage is "reused" and the
//lifetime of an object of type T is started.
//Old object's destructor is not called so any
//program that depends on the side effects
//produced by the destructor has undefined behavior
//(3.8 [basic.life] p.4)
//T's constructor is not called so any program
//that depends on the side effects produced by
//the constructor has undefined behavior.
T* t = as_if_ctor_was_already_called<T>(storage);
U* u = as_if_ctor_was_already_called<U>(storage);
V* v = as_if_ctor_was_already_called<V>(storage);
Now let me ask some questions...
a) Would this have some impact in the performance of the code produced
by current C++ compilers?
b) If a)'s answer is "no", could "as_if_ctor_was_already_called<T>" be
c) If b)'s answer is "yes", wouldn't this allow C compatibility?
SG12 list run by herb.sutter at gmail.com