Using the new constructor list in the initializer member

This compiles, but I never saw it in any other code. It is safe?

Testclass():sources(new int[32]){}

Instead:

Testclass(){
 sources=new int[32];
 }
+5
source share
2 answers
Testclass():sources(new int[32]){}

Using member-initialization-list , which is the preferred method of initializing members.

By "safe" or "good," you probably meant, is it safe? What if newthrows a bad_alloc exception?

Well, in this case, the destructor will not be called , because the object is not completely constructed, since the constructor body is not executed. A resource leak may occur if you purchase a resource in the initialization list.

,

class X
{
    int  *ints;  //order of declaration matters!
    Huge *huges; //it ensures that huges will be initialized after ints

    X() : ints(new int[32]), huges(new Huge[10000]) {}
};

new Huge[10000] , , ints, !

function-try-block. :

, , , , . , , , , , , catch -try-block. .

, , .

+9

, ++ try/catch :

class C {
    int *n;
public:
    C();
};

C::C()
try : n(new int[100])
{
  // do stuff here
}
catch(...)
{
  // handle exceptions
}

int main()
{
    C c; // Should be safe...
}
0

All Articles