I would like to allocate and array of classes on the stack without calling the constructor. The following example clarifys:
template<class t,int SetNum> class set
{
private:
t Storage[SetNum];
};
class myClass
{
private:
int* Array;
public:
myClass()
{
Array=new int[10];
}
}
int main()
{
set<myClass,10> Set;
}
I do not want to allocate the 10 new ints for Array that occurs when myClass‘s constructor is called, but still want the space allocated for myClass.
You have to have an array of
unsigned chars (or such) to use as “backing storage” for your elements, and then call the placementnewoperator (see e.g. here) to construct your instances there (which, by the way, is whatstd::vectoralready does).Warning: if you use placement new you have the responsibility to deallocate manually the objects you created with it, calling explicitly the destructor; also, the pointer you pass to placement new must be properly aligned for the objects you are creating, otherwise bad stuff may happen.
See also this question.
Example of a twisted mix of
std::arrayandstd::vectorbuilt with the techniques described (requires C++11 for theuniontrick to work):Output:
Edit there’s a much simpler way to get aligned storage.