Reputation: 30615
If I have a class like so (forgive the rough syntax):
class Z{
public:
void method1();
void method2(vector<X>& v);
void method3(vector<X>& v);
private:
std::vector<X> myvec;
}
and basically I want to pass myvec from method1() through method2() to method3() where it will be modified. If my method1() looks like this:
void Z::method1(){
vector<X> v = z::myvec; //What do I have to do with this line so that the changes
method2(v); //made to v in method3() are permanent and not lost once
} //method1() returns?
void Z::method2(vector<X>& v){
method3(v);
}
//Modify vector<X> myvec
void Z::method3(vector<X>& v){
v.push_back(<something>);
}
How could I change the vector in method3() so that once method1() returns, the changes made to the vector are permanent and not lost?
Upvotes: 1
Views: 116
Reputation: 4329
I dont know why you exactly wanted this flow, method1()-->method2()-->method3(). If this is something that is not intentional you can directly use data member myvec in method3(). But I am sure this could not be the case, there must be a use case because of which you are using it.
for the other way, you can modify, method1() in this way.
void Z::method1(){
method2(z::myvec);
}
and keep rest of the function as it is.
Actually what's happening in your case is in your method1() you are actually creating new object and passing that new object with reference so all that changes is being made to that new vector not the original vector.
vector<X> v = z::myvec; // this creates new object.
You test is with debugging.
please let me know if this answers your doubt.
Upvotes: 1
Reputation: 234665
Why not just allow method3 to use the class' member data directly? That's a perfectly normal thing to do.
void Z::method3(){
myvec.push_back(<something>);
}
But if you really want to do it your way (and I would advise against it as it's so idiosyncratic), replace your first commented line with
vector<X>& v = z::myvec;
Upvotes: 2
Reputation: 96800
Just make v
a reference:
vector<X>& v = myvec;
or simply pass myvec
itself:
method2(myvec);
Upvotes: 3