while writing a offset array class(your idxs go from lets say 100 to 1000, so you create class that takes that into account without wasting first 100 slots in the array) I ran into a problem.
How to initialize a class that has an C array of elements(problem is that T doesnt have def constructor). Basically I want the array to be totally uninitiated. Example:
class MyClass
{
MyClass(int i)
{
}
};
template <typename T, size_t n, size_t offset>
struct offsetedIdxArray
{
T data[n];// error line : error C2512: 'MyClass' : no appropriate default constructor available
offsetedIdxArray()
{
}
T& operator [](size_t pos)
{
return data[(pos-offset)];
}
};
usage:
offsetedIdxArray<MyClass, 1024,offset> oia;
Making def constructor is not the option because class I use is in fact library class.
*EDIT: * not related to problem described here, but it turned out that my precious library class doesnt have copy ctor, just move ctor, so I had to use vector of unique_ptr.
To get a statically-sized uninitialized portion of storage, you can use an “untyped” buffer of aligned storage, like
std::aligned_storage<sizeof(T[n]), alignof(T)>::typein C++11 (in C++03 you need to use achar[sizeof(T[n])+something]and do manual corrections for alignment, or use achar[sizeof(T[n])]and compiler extensions to specify alignment).That means using placement new for constructors, and explicit destructor calls for destruction. It is up to you to track what parts of that storage have objects (and thus needs destruction) and what parts don’t have objects (and can’t have destructors called on). It is also up to you to cater for when the client requests an element that isn’t initialized at all (there’s no object at the place it’s supposed to be).
An alternative is to use an array of
boost::optionals, and then you don’t have to care about destruction and can simply assign new elements to their respective index.