Reputation: 421
In this code:
using namespace std;
int main() {
int x = 11;
int* rawPointer = &x;
unique_ptr<int> integerPointer = make_unique<int>(x);
cout << *rawPointer << std::endl;
x++;
cout << *rawPointer << std::endl;
return 0;
}
when we ask for the value of rawPointer
, the output is :
11
12
which is correct. But when we ask for the value of integerPointer
, which happens to be a unique pointer
, we get the output :
11
11
I would have thought that it would behave just like rawPointer
. Why is that? Is that really the way unique pointers
work?
Thanks
Upvotes: 0
Views: 75
Reputation: 2539
From the std::unique_ptr reference docs:
Constructs an object of type T and wraps it in a std::unique_ptr.
So you're constructing a new copy, managed by the unique_ptr
by passing x
, and not managing x
by address.
Upvotes: 1