Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why dereferencing a unique_ptr won't modify the original object

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
like image 606
Emerson Xu Avatar asked Dec 18 '22 13:12

Emerson Xu


1 Answers

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

like image 190
songyuanyao Avatar answered Jan 03 '23 01:01

songyuanyao