如何返回对函数参数传递的引用的引用?

Mic*_*ael 2 c++ pointers arguments copy reference

好的,所以我要做的是传递对函数的引用,然后返回相同的引用而不复制.我不想使用move,因为它可以"清空"原始变量的内容.这是我想要的伪代码

a;    
b = func(a);    
change(b); // a changes as well
Run Code Online (Sandbox Code Playgroud)

我知道你可以使用指针(auto*b =&a)来做到这一点,但我想知道是否可以用函数完成.这是我试过的:

#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();
}
Run Code Online (Sandbox Code Playgroud)

打印什么

vec1[0]=0 vec1[1]=1
vec2[0]=1000 vec2[1]=1
vec3[0]=0 vec3[1]=999
Run Code Online (Sandbox Code Playgroud)

我想要的是

vec1[0]=1000 vec1[1]=999
vec2[0]=1000 vec2[1]=999
vec3[0]=1000 vec3[1]=999
Run Code Online (Sandbox Code Playgroud)

我知道我的矢量在某些时候被复制(在参数和/或返回中)并且我不希望这样.

jca*_*cai 5

vector<int> &vec3 = returnRef2(vec1);而不是vector<int> vec3 = returnRef2(vec1);.