Wei-Shou Yang
Wei-Shou Yang

Reputation: 11

How to get the returned reference to a vector?

I found two ways to get the reference returned by the function.

vector<int> vec1 = {4,5,6};

vector<int>& rtn_vec(void)
{
    return vec1;
}

int main()
{
    vector<int> &vec2 = rtn_vec(); //way 1
    vector<int> vec3 = rtn_vec(); //way2

    vec2[0] = 3;

    return 0;
}

I understand way 1 means passing the reference to vec1 to &vec2, so vec2[0] = 3; changes vec1 to {3,5,6}.

But about way 2, I have 2 questions:

  1. Why can I pass a reference (vector<int>&) to an instance (vector<int>), how does it work?

  2. Does way 2 involve deep copy? Because I run this code and vector<int> vec3 = rtn_vec(); seems just copy vec1 to vec3.

Upvotes: 1

Views: 100

Answers (2)

Petr
Petr

Reputation: 9997

vector<int> vec3 = rtn_vec(); //way2

This allocates a new vector and invokes a copy constructor, so yes, this is "deep" copy.

Actually, this is in no way different from simply writing

vector<int> &vec2 = vec1;
vector<int> vec3 = vec1;

Or to make things even clearer

vector<int> &return_value = vec1;
vector<int> &vec2 = return_value;
vector<int> vec3 = return_value;

(Though be careful with term "deep". If it was vector<int*>, then only the pointers would be copied, not the ints themselves.)

Upvotes: 5

Toby Speight
Toby Speight

Reputation: 30827

When you copy-construct vec3, a shallow copy is made (C++ doesn't really do "deep" copy). All the elements in the vector are copied by value, just as with any other copy of a std::vector.

Upvotes: 0

Related Questions