[英]C++ shared_ptr and built-in pointer
Delete twice built-in pointers cause undefined, but what happened in this situation? 删除两次内置指针会导致未定义,但是在这种情况下会发生什么? In this code, is shared pointer undefined?
在此代码中,共享指针是否未定义?
string *str_1 = new string;
std::shared_ptr<string> str_ptr(str_1);
*str_1 = "C++";
cout << *str_ptr << endl;
*str_ptr = "C#";
cout << *str_1 << endl;
// str_1 & str_ptr refers same piece of memory
delete str_1;
cout << *str_ptr << endl; // Is this undefined?
Your code is undefined because after the call to deletion of the raw pointer, the shared_ptr
is left with a dangling pointer reference. 您的代码未定义,因为在调用删除原始指针之后,
shared_ptr
留下了一个悬空的指针引用。 You then proceed to dereference the already freed memory (undefined behavior 1). 然后,您可以取消引用已经释放的内存(未定义的行为1)。 When the
shared_ptr
goes out of scope, it will call delete
on the pointer it was told to manage, which is freeing already freed memory (undefined behavior 2). 当
shared_ptr
超出范围时,它将在被告知要管理的指针上调用delete
,这将释放已释放的内存(未定义的行为2)。
As a convenience, shared_ptr
allows initialization from a raw pointer, but you are supposed to allow it to manage the allocated memory afterwards. 为方便起见,
shared_ptr
允许从原始指针进行初始化,但是您应该允许它随后管理分配的内存。 It is an error to manage the raw pointer (eg, delete it or initialize another shared_ptr
) when you have given it to shared_ptr
. 这是管理的原始指针(例如,删除或初始化另一个错误
shared_ptr
),当你给它shared_ptr
。
It is actually better practice, when using shared_ptr
to use the helper function make_shared
. 当使用
shared_ptr
来使用辅助函数make_shared
时,实际上是更好的做法。
std::shared_ptr<std::string> sp = std::make_shared<std::string>("C++");
This format avoids you having to deal with creating a raw pointer. 这种格式避免了您不得不创建原始指针的麻烦。 It also turns out to be more efficient because it avoids an extra allocation the smart pointer would have to do if it was passed a raw pointer.
事实证明,它也更有效,因为它避免了智能指针在传递原始指针时必须做的额外分配。
sharped_ptr
is no magic. sharped_ptr
并不是魔术。 It simply calls delete
once the last shared_ptr
to an object is destroyed. 一旦销毁了对象的最后一个
shared_ptr
,它便简单地调用delete
。 Thus, your code calls delete
twice, once when you delete str_1
and then when str_ptr
goes out of scope. 因此,您的代码调用两次
delete
,一次是删除str_1
,然后是str_ptr
超出范围。 Thus, using a shared_ptr
doesn't change anything in comparision to calling delete
twice explicitly: The result is undefined behaviour. 因此,与显式调用两次
delete
相比,使用shared_ptr
不会发生任何变化:结果是未定义的行为。
shared_ptr
was invented to take the burden of explicit delete
calls from you. shared_ptr
发明是为了承担来自您的显式delete
调用的负担。 Thus, there is also simply no reason for using shared_ptr
and explicit delete
together. 因此,也完全没有理由同时使用
shared_ptr
和显式delete
。 So even if it did not result in undefined behaviour, my advice would still be: Don't do it! 因此,即使它没有导致不确定的行为,我的建议仍然是: 不要这样做!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.