+ 1

Garbage value in smart pointers

I'm creating a linked list which utilises shared smart pointers, and after fixing some compiler errors i noticed that the values that i gave the nodes were being completely ignored and replaced with values like 3608472 on sololearn, and 842150451 on visual studio. what am i doing wrong here? i tried using raw pointers for the temporary pointers, but then the program wouldn't even compile. source code: https://code.sololearn.com/ciugC1DWJ1Q4

21st Dec 2017, 12:04 PM
X-1
X-1 - avatar
1 Réponse
+ 2
I found this on www.cplusplus.com/reference/memory/shared_ptr "shared_ptr objects can only share ownership by copying their value: If two shared_ptr are constructed (or made) from the same (non-shared_ptr) pointer, they will both be owning the pointer without sharing it, causing potential access problems when one of them releases it (deleting its managed object) and leaving the other pointing to an invalid location." Perhaps this is what happens in your case as well? You copy a temporary shared pointer to the original pointer, but on deletion of the temporary pointer, the original gets deleted as well? So you should use unique_ptr instead or use weak_ptrs with shared_ptrs in places where you declare temporary pointers for copying.
22nd Dec 2017, 5:31 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar