Initialization in the constructor

I have seen many codes where encoders define the init () function for classes and call it the first after instantiating.

Is there any harm or restriction on all initializations in the constructor?

+5
source share
6 answers

This is a design template that is associated with exceptions that were selected from within the constructor of the object.

In C ++, if an exception is thrown from within the costructor object, then this object is considered unconstructed in general, by the execution language. As a result, the destructor object will not be called when the object goes out of scope.

This means that if your constructor had the following code:

int *p1 = new int;
int *p2 = new int;

and the code in this destructor:

delete p1;
delete p2;

p2 - , bad_alloc new. , p1 . , , p1.

, , , .

, .

Herb Sutter: ++

0

, :

class stuff 
{
public:
    stuff(int val1) { init(); setVal = val1; }
    stuff()         { init(); setVal = 0; }

    void init()     { startZero = 0; }

protected:
    int setVal;
    int startZero;
};
+2

: . ++ "" , , , . Java ( private final), , .

, init(), , . ( ++, , .)

+2

Java , init():

  • , , , super
  • , ,
+1

. , , , . , , . , .

, , , . , , , .

, , , . , , . , , . , , .

0

, , , . ( / , ?)

, , - , , .

Since it is not possible to complete all initialization in constructors, at least part of the initialization must be performed in init functions. This leads to the question: what parts should be executed in init functions? A flexible choice is to do all the initialization of the pointer in the init functions. Then you can create objects in any order, because when creating this object you do not need to worry about whether you already have pointers to other objects that he needs to know about.

0
source

All Articles