Most posts probably ask question as to why something is not working; mine is to ask why something IS working…
I thought that the only way to dynamically allocate memory was with the use of new or malloc in cpp, but this is apparently wrong. The following code both compiles and works, but cannot figure out why!
int x;
cin >> x;
valarray<double> data(x);
// initializing elements and printing the array both work fine....
It is driving me crazy. x is not known at compile time, only at run time, and I am not doing:
int x;
cin >> x;
valarray<double> *data;
data = new valarray<double> (x);
...
As you would to dynamically allocate an array. I apparently have a fundamental flaw of memory allocation.* Can someone shed light as to why both of these work??
EDIT: I edited my question to make the actual question I am looking for more clear.
The dynamic memory allocation is hidden inside of the constructor of the
valarrayclass and still usesnewormallocin the end.Instead of
valarrayyou could also use avector. Both classes can be resized at runtime.That the complexity is hidden behind the interface of the classes is an advantage. You don’t ever have to remember to call
deletesince the destructor of the class will take care of that even when exceptions are beeing thrown; they are exception safe!