See the following example, I've used a unique pointer and a raw pointer to a
, my question is, why does the raw pointer work but not the unique pointer? If I want to modify string a
like a reference by using the unique_ptr
or shared_ptr
, what should I do?
Example program:
#include <iostream>
#include <string>
#include <memory>
int main()
{
using namespace std;
string a = "aaa";
auto ptr = std::make_unique<string>(a);
auto ptr2 = &a;
cout << "before, a: " << a << endl;
*ptr += "bbb";
cout << "After, a: " << a << endl;
*ptr2 += "ccc";
cout << "after 2, a: " << a << endl;
}
Output:
before, a: aaa
After, a: aaa
after 2, a: aaaccc
std::make_unique<string>(a);
will new
a brand new std::string
(initialized from a
), which is pointed by ptr
later. So the object is modified by *ptr += "bbb"
, but it has nothing to do with the original object a
.
You could confirm that the object pointed by unique_ptr
is modified, via the following demo:
string* pa = new string("aaa");
unique_ptr<string> ptr(pa);
auto ptr2 = pa;
cout << "before, *pa: " << *pa << endl;
*ptr += "bbb";
cout << "After, *pa: " << *pa << endl;
*ptr2 += "ccc";
cout << "after 2, *pa: " << *pa << endl;
Result:
before, *pa: aaa
After, *pa: aaabbb
after 2, *pa: aaabbbccc
LIVE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With