0

Do you have any idea why is this error happening;

https://code.sololearn.com/c6413tiKkr2V/?ref=app Lines: 25 and 28 Also I really don't want extra allocations. Is there any way to have the same result but without the new keyword?

15th Dec 2020, 3:37 PM
xaralampis_
xaralampis_ - avatar
2 Answers
+ 3
Note that by doing v.push_back(&i) you're storing pointers to local variables.The range-based for loop is creating local copies of B objects found in vector b, then assigns them to the variable i. Any attempt to access these pointers at another point in the code will result in a seg. fault. The fix? Add an ampersand(&) after auto to create references of the B objects in b, instead of creating local copies
15th Dec 2020, 4:43 PM
Anthony Maina
Anthony Maina - avatar
0
Anthony Maina wow really I thought that the base ranged for loop returned references of the original object. Even though it doesn't make much sence now that I think about it.. Thanks a lot!
15th Dec 2020, 5:44 PM
xaralampis_
xaralampis_ - avatar