Posts

Showing posts from April 17, 2019

How to get the returned reference to a vector?

Image
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box; 1 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: Why can I pass a reference ( vector<int>& ) to an instance ( vector<int> ), how does it work? Does way 2 involve deep copy? Because I run this code and vector<int> vec3 = rtn_vec(); seems just copy vec1 to vec3 . c++ reference return-value share | improve this question edited Nov 15 '18 at 15:16 Toby Speight 17.6k 13 44 69 asked Nov 15