+ 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
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.
+ 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.
+ 1
Oh ok...i thought something of emplace with reference wrapper...yes, emplace does create object in container memory itself
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 ?