If I take a raw pointer to unique_ptr and then use reset, is the raw pointer valid?

For example, I'm sure this works.

int foo = 51; int* bar = &foo; foo = 3; 

So the bar is still valid and *bar == 3 .

And if we say

 std::unique_ptr<int> foo(new int(51)); // should probably use make_unique int* bar = foo.get(); foo.reset(new int(3)); 

I'm sure *bar == 3 ? Or am I invoking undefined behavior while continuing to reference the bar?

+5
source share
3 answers

No, absolutely not. You will get undefined behavior since the raw pointer controlled by unique_ptr changes to reset . In fact, unique_ptr removes the managed pointer and redistributes the new one, so your old pointer will point to the old address, which is no longer valid. Your code is equivalent to this:

 #include <iostream> int main() { 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 piece of code is really correct, since you are not changing any address there, you are just changing the variable that the pointer points to, so disclosing the pointer will give you an updated value.

+8
source

No, if you reset a unique_ptr , it will delete the pointer it owns.

You can do:

 int* bar = foo.release(); 

This causes foo to give up ownership of its pointer and return it.

+7
source

No, std :: unique_ptr.reset will delete the existing pointer.

See http://www.cplusplus.com/reference/memory/unique_ptr/reset/

Use release for your purpose.

0
source

All Articles