Eg I'm pretty sure this works.
int foo = 51;
int* bar = &foo;
foo = 3;
So bar is still valid, and
*bar == 3.
What about if we say
std::unique_ptr<int> foo(new int(51)); // should probably use make_unique
int* bar = foo.get();
Am I guaranteed that
*bar == 3? Or am I causing undefined behavior by continuing to reference bar?
Best How To :
No, not at all. You will get undefined behaviour, as the raw pointer managed by the
unique_ptr is changed by the
reset. In fact, the
unique_ptr deletes the managed pointer and reallocates a new one, so your old pointer will keep pointing to the old address, which is no longer valid. Your code is equivalent to this:
int* managed = new int(51); // equivalent to unique_ptr(new int(51));
int* bar = managed; // equivalent of unique_ptr::get
delete managed; managed = new int(3); // equivalent to unique_ptr::reset(new int(3))
std::cout << *bar << std::endl; // Wrong!!! Undefined behaviour, bar is dangling!
Your first code snippet is indeed correct, since you are not changing any address there, you are just changing the variable the pointer points to, so of course dereferencing the pointer will get you the updated value.