c++ - Are there any issues with allocating memory within constructor initialization lists? -



c++ - Are there any issues with allocating memory within constructor initialization lists? -

i have used initialization lists great deal in c++ programs wasn't aware allocate memory within them.

so can (as contrived example) 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 issues in doing memory allocation in way? regarding order of initialization here safe have parameter initialized 1 initialized in same list? i.e. allocate count before utilize safe utilize or there special initialization order fall foul of?

it's not exception-safe. if new j throws exception destructor test not called, , memory i not freed.

the destructor of i called if initializer j throws, it's raw pointer has no destructor. create exception-safe replacing i suitable smart pointer. in case, unique_ptr<int> i , unique_ptr<int[]> j do.

you can rely on initializers executed in right order (the order members defined, not order in list). can safely utilize info members have been initialized, there's no problem using count in initializer k.

c++

Comments

Popular posts from this blog

How do I check if an insert was successful with MySQLdb in Python? -

delphi - blogger via idHTTP : error 400 bad request -

postgresql - ERROR: operator is not unique: unknown + unknown -