[英]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? 请看下面的例子,我用了一个独特的指针和一个原始指针到
a
,我的问题是,为什么原始指针工作,但不是唯一的指针? If I want to modify string a
like a reference by using the unique_ptr
or shared_ptr
, what should I do? 如果我想使用
unique_ptr
或shared_ptr
修改字符串a
像引用,我该怎么办?
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. 将
new
一个全新的std::string
(从a
初始化),稍后由ptr
指出。 So the object is modified by *ptr += "bbb"
, but it has nothing to do with the original object a
. 因此,对象由
*ptr += "bbb"
,但它与原始对象a
无关。
You could confirm that the object pointed by unique_ptr
is modified, via the following demo: 您可以通过以下演示确认
unique_ptr
指向的对象已被修改:
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
std::unique_ptr
must refer to a dynamically allocated object (so that it can safely delete it in the end). std::unique_ptr
必须引用动态分配的对象(以便最终可以安全地删除它)。 That's why std::make_unique
creates a new object. 这就是为什么
std::make_unique
创建一个新对象的原因。
This will work up to your expectations : 这将符合您的期望 :
#include <iostream>
#include <string>
#include <memory>
int main()
{
using namespace std;
string* a = new string("aaa");
std::unique_ptr<string> ptr(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: aaabbb
after 2, a: aaabbbccc
Because std::make_unique<string>(a)
creates a completely new std::string
object and initializes it with the contents of a
. 因为
std::make_unique<string>(a)
创建一个全新std::string
对象,并使用的内容对其进行初始化a
。 The new string and the old a
have no connection with each other. 新的字符串和老
a
有彼此没有任何联系。
Make unique constructs an object of the type T and wraps it in a unique_ptr. 使唯一构造成为T类型的对象,并将其包装在unique_ptr中。 You may be actually making a copy of "a" without you noticing it.
您可能实际上在没有注意到它的情况下复制“a”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.