Lately I'm working on a project that use raw pointers in some places in code, everything seems fine and I want to upgrade my code by using smart pointers just for safety like everyone says, but it turns out the wrong results.
I was looking for the bug for hours until I realized this fatal inconvenience of shared_ptr that I will just only summarize that in this little experiement showed below.
This is the experiment code:
int main() {
// code 1
int arr[5] = { 1, 5, 6, 7, 9 };
cout << &arr[2] << endl;
shared_ptr ptr = make_shared<int>(arr[2]);
cout << ptr << "\n";
// code 2
cout << &arr[2] << endl;
int* ptr1 = &arr[2];
cout << ptr1 << "\n";
}
Basically, what I'm doing here is that I want a pointer that points to an element in the array (my project uses vector, but this experiment uses array still gives the same issue) contains the same address of that element, for example in //code 2 (old method using raw pointer) those 2 cout commands will give the same result, but not for //code 1 when it just prints out 2 separate addresses.
After debugging for about half a minute, I realized that this line make_shared<int>(arr[2]) in code 1 will create the poniter that points to an address that has the same value as the element in the array but not points to the element in the array, which is quite inconvenient because I was expecting it to act like code 2.
additional info: When I asks chatgpt will the code 1 give the same result, it answers "yes", which proves that this problem is not as obvious for many people.
By the way, any suggest for fix? Thank you.