Easy c++ question regarding valarray
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 fu开发者_如何学Gondamental 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 valarray
class and still uses new
or malloc
in the end.
Instead of valarray
you could also use a vector
. 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 delete
since the destructor of the class will take care of that even when exceptions are beeing thrown; they are exception safe!
valarray<double> (x)
invokes the constructor and although the object is already allocated (on the stack), you allocate the elements of the array through this constructor. Allocating the elements is done internally in the constructor.
new valarray<double> (x)
does the same, but it allocates the object itself as well, because new
is used. So the object as well as the array elements will be stored on the heap.
The line
valarray<double> data;
is automatically creating a valarray<double>
object on the stack and is calling the no-argument constructor.
The line
data = valarray<double> (x);
translates to
data.operator=(valarray<double> (x));
which calls the valarray constructor that takes an int. What ends up happening is that another object is automatically created on the stack and is then assigned to the first object.
Note that it would be better to do
valarray<double> data(x);
so that you only create one object instead of creating two and throwing one away.
Edited to address other OP comments
x
is not unknown. The cin >> x;
line in your program is setting x
. So when the valarray
constructor is called it is being passed an actual value. At the bottom it's no different than this (though of course since the memory allocation is internal to valarray
it can make sure to delete
automatically it when the object goes away):
int* makeArray(int size) {
return new int[size];
}
int main() {
int s;
cin >> s;
int* theArray = makeArray(s);
// do stuff
return 0;
}
精彩评论