I'm attempting to create a type-agnostic vector in C++ that is distinguished by two things. First, it allocates the memory in the object itself, at least until a certain point, rather than maintaining the actual array of objects on the heap. Secondly, it can't use C++'s copy/assign constructors, which appears to slow down the code and is not necessary.
While looking through the codebase I maintain on my computer, I found a class in LLVM's codebase that pretty much perfectly describes what I'm looking for: SmallVector.h. Being relatively new to C++, I'm not entirely sure why some of the design decisions were made. For instance, why is the array allocated in terms of U
rather than T
? The comment gives a clue:
If T has a ctor or dtor, we don't want it to be automatically run, so we need to represent the space as something else. An array of char would work great, but might not be aligned sufficiently. Instead we use some number of union instances for the space, which guarantee maximal alignment.
U
, of course, refers to the following union:
union U {
double D;
long double LD;
long long L;
void *P;
} FirstEl;
So, I guess, here are my true questions: Why does allocating an array of T
imply that constructors/destructors are called? Is there any way to move c++ object instances around, i.e. in and out of the vector, without calling these constructors/destructors? I guess I can just use LLVM's SmallVector
implementation, but I hate using code without understanding it.
Best, Duane
C++'s copy/assign constructors, which appears to slow down the code...
It makes correct code, because they are necessary. There are several classes that will crash if they are ever memcopied, and do not have a default constructor.