Easy c++ question regarding valarray-Collection of common programming errors

The line

valarray data;

is automatically creating a valarray object on the stack and is calling the no-argument constructor.

The line

data = valarray (x);

translates to

data.operator=(valarray (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 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;
}