What's wrong in this reference wrapper code? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

What's wrong in this reference wrapper code?

Please refer below code: I just wanted to avoid copy and used reference wrapper for vector of class objects. Destructor is called as vec is local to function. How to avoid destructor call and allow object to be accessed in main function inside for loop ? https://code.sololearn.com/chF0Nekl6MjS/?ref=app

12th Mar 2022, 8:37 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
4 Answers
+ 1
reference_wrapper was not a good choice for that because you are referencing local variables that exist only within getAllData() method. Use unique_ptr instead or just Test type with vector::emplace method instead of initialization_list.
6th Jun 2022, 1:29 PM
Victor Cortes
Victor Cortes - avatar
+ 1
Ketan Lalcheta here comes an example using emplace: https://code.sololearn.com/cE7rwxzs0o66/?ref=app Note that the container does not make any copy.
8th Jun 2022, 5:04 PM
Victor Cortes
Victor Cortes - avatar
+ 1
Oh ok...i thought something of emplace with reference wrapper...yes, emplace does create object in container memory itself
8th Jun 2022, 5:42 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
Thanks Victor Cortes I got your point about unique pointer... but not able to use emplace... tried below but no success: vector<reference_wrapper<Test>> vec = {emplace(6),emplace(8),emplace(9)} ; could you please help or suggest on this ?
8th Jun 2022, 3:37 PM
Ketan Lalcheta
Ketan Lalcheta - avatar