I have used initialization lists a great deal in my C++ programs but wasn’t aware that you could allocate memory within them.
So you can do something (as a contrived example) like this:
class Test
{
private:
int* i;
int* j;
int count;
int* k;
public:
Test(void) : i(new int), j(new int[10]), count(10), k(new int[count])
{
}
~Test(void)
{
delete i;
delete [] j;
delete [] k;
}
};
Are there any issues in doing memory allocation in this way? Regarding the order of initialization here is it safe to have a parameter initialized by one initialized in the same list? i.e. as I allocate count before I use it is it safe to use or is there some special initialization order I could fall foul of?
It’s not exception-safe. If the
newforjthrows an exception then the destructor forTestis not called, and so the memory foriis not freed.The destructor of
iis called if the initializer forjthrows, it’s just that a raw pointer has no destructor. So you could make it exception-safe by replacingiwith a suitable smart pointer. In this case,unique_ptr<int>foriandunique_ptr<int[]>forjwould do.You can rely on the initializers to be executed in their correct order (the order the members are defined, not necessarily the order in the list). They can safely use data members that have already been initialized, so there’s no problem with using
countin the initializer fork.