Michael
Michael

Reputation: 53

How to return a reference to the reference passed in function argument?

Ok, so what I'm trying to do is pass a reference to a function, then return that same reference without copying. I don't want to use move because that can "empty" the contents of the original variable. This is what I want in pseudo code

a;    
b = func(a);    
change(b); // a changes as well

I understand you can do this with pointers ( auto * b = &a), but I want to see if it can be done with a function. This is what I tried:

#include <vector>
#include <iostream>
using namespace std;
template<class T>
T& returnRef1(T* t){
    return *t;
}
template<class T>
T& returnRef2(T& t){
    return t;
}

int main(){
    vector<int> vec1 = { 0, 1, 2, 3, 4 };
    auto * p2v = &vec1;
    vector<int>  vec2 = returnRef1(p2v);
    vector<int> vec3 = returnRef2(vec1);
    vec2[0] = 1000;
    vec3[1] = 999;
    cout << "vec1[0]=" << vec1[0] << " vec1[1]=" << vec1[1] << endl;
    cout << "vec2[0]=" << vec2[0] << " vec2[1]=" << vec2[1] << endl;
    cout << "vec3[0]=" << vec3[0] << " vec3[1]=" << vec3[1] << endl;
    cin.get();
}

what prints

vec1[0]=0 vec1[1]=1
vec2[0]=1000 vec2[1]=1
vec3[0]=0 vec3[1]=999

what i want

vec1[0]=1000 vec1[1]=999
vec2[0]=1000 vec2[1]=999
vec3[0]=1000 vec3[1]=999

I understand that my vector is getting copied at some point(either in arguments and/or return) and I don't want that.

Upvotes: 2

Views: 95

Answers (1)

jcai
jcai

Reputation: 3583

Use vector<int> &vec3 = returnRef2(vec1); instead of vector<int> vec3 = returnRef2(vec1);.

Upvotes: 5

Related Questions