Allocation as default initialization

  • A+
Category:Languages

Say I have a struct (or class) with a dynamic array, its length, and a constructor:

struct array {     int l;     int* t;     array(int length); };  array::array(int length) {     l=length;     t=new int[l]; } 

I assume everything so far is legal: this is how I would write it (although it maybe not be the only way to do things), but I have seen the following code, that somewhat seems to work:

struct array {     int l;     int* t = new int[l];     array(int length); }  array::array(int length) {     l=length; } 

It looks bad, so I wonder if this works out of sheer luck and undefined behaviors, or if there is some internal rule that makes this code work fine.

 


This code is not correct.

int* t = new int[l]; will happen before l=length;, thus reading the uninitialized variable l. Member initializers are handled before the constructor's body runs.

array::array(int length) : l{length} {} 

instead would work because l is declared before t.

However, doing this "by hand" is a bad idea to begin with. You should be using std::vector.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: