Bob Bob - 11 months ago 29
C++ Question

Vector data disappears after function exits

I have a custom vector class called VEC and a class called Data that holds a std::vector of VECs called v. VEC acts as a very simple vector that just stores 4 values.

vector<VEC> v;

Elsewhere, I have two functions; process and create. My process() is supposed to accept a Data object as a parameter and then alter its contents. It is declared as

void myClass::process(Data data);

Inside this function, I create a temporary vector of VECs, then push it's contents into data's v:

VEC v1(1, 1, 1, 1);
VEC v2(2, 2, 2, 2);
VEC v3(3, 3, 3, 3);
vector<VEC> temp;

for (int i = 0; i < 3; i++)
cout << data.v.size() << endl;

As you would expect, this prints out 3.

Now here's where the problem happens. The other function create() calls process() on every Data object in the vector datalist. For testing purposes, this one only uses the first element.

void myClass::create() {
cout << dataList[0].v.size() << endl;

This is what it prints out


As you can see, it works properly in the process() function, but the v vector seems to empty itself as soon as that function exits. This is a problem, because I need each Data object to save it's new v contents after process() is called. What's going on here?

Answer Source

If you want to manipulate your Data object, your process function must be declared as such:

void myClass::process(Data& data);

You have to pass by reference, else a copy of data will be made when you pass it to the function. The ampersand (&) after Data in the above function prototype means "take a reference to a variable data of type Data."

The way you had it, any changes the function makes to data will be done only to this local variable. Thus, the changes will be destroyed when the process function exits.