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
12/21/2017 12:04:34 PMX-1
1 AnswerNew Answer
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.