I had a function that returns a unique_ptr to an array element, and I noticed the original variable was not getting updated.
Why does this work (a[5] == 6 after):
int a[10];
for (size_t i = 0; i < 10; i++)
{
a[i] = i;
}
int* ap = &a[5];
*ap += 1;
But
int a[10];
for (size_t i = 0; i < 10; i++)
{
a[i] = i;
}
unique_ptr<int> ap = make_unique<int>(a[5]);
*ap += 1;
Does not update the original array element? (a[5] == 5 ):
The function std::make_unique<T>
constructs a new object .
Quoting:
Constructs an object of type T and wraps it in a std::unique_ptr.
Therefore, your statement
unique_ptr<int> ap = make_unique<int>(a[5]);
creates another integer ( T = int
) and initializes it with the value of the expression a[5]
.
So, when you operate on the pointer ap
you are actually modifying another integer (a copy of a[5]
).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.