- #1
JonnyG
- 234
- 45
When I run this simple code:
45 is printed on the console. I expected this to print 3 to the console. It prints 3 when I use a built-in pointer. Does this mean that unique pointer doesn't actually point to x itself (i.e. doesn't hold x's memory address)? If in the above code I add this line to the end:
cout << *q.get();
Then it prints 3 to the console. This means that the built-in pointer that is in q points to an object that was indeed changed to point to a memory address that contains 3 in it (but this pointer was supposed to point to x!).
Furthermore, when I run this:
Then the console prints 3, as I had wanted, but then the program crashes. There is obviously something about unique pointers (and shared pointers in general) that I am not understanding. I'd appreciate some help.
C++:
int main() {
int x = 45;
std::unique_ptr<int> q(new int (x));
*q = 3;
cout << x << endl;
}
45 is printed on the console. I expected this to print 3 to the console. It prints 3 when I use a built-in pointer. Does this mean that unique pointer doesn't actually point to x itself (i.e. doesn't hold x's memory address)? If in the above code I add this line to the end:
cout << *q.get();
Then it prints 3 to the console. This means that the built-in pointer that is in q points to an object that was indeed changed to point to a memory address that contains 3 in it (but this pointer was supposed to point to x!).
Furthermore, when I run this:
C++:
int main() {
int x = 45;
int *p = &x;
std::unique_ptr<int> q(p);
*q = 3;
cout << x << endl;
}
Then the console prints 3, as I had wanted, but then the program crashes. There is obviously something about unique pointers (and shared pointers in general) that I am not understanding. I'd appreciate some help.