C ++来自同一原始指针的多个唯一指针 [英] C++ multiple unique pointers from same raw pointer
问题描述
在下面考虑我的代码.我对唯一指针的理解是,只能使用一个唯一指针来引用一个变量或对象.在我的代码中,我有多个unique_ptr访问同一个变量.
Consider my code below. My understanding of unique pointers was that only one unique pointer can be used to reference one variable or object. In my code I have more than one unique_ptr accessing the same variable.
我知道,使用智能指针显然不是正确的方法,因为指针应具有创建后的完全所有权.但是,为什么这是有效的却没有编译错误呢?谢谢.
It's obviously not the correct way to use smart pointers i know, in that the pointer should have complete ownership from creation. But still, why is this valid and not having a compilation error? Thanks.
#include <iostream>
#include <memory>
using namespace std;
int main()
{
int val = 0;
int* valPtr = &val;
unique_ptr <int> uniquePtr1(valPtr);
unique_ptr <int> uniquePtr2(valPtr);
*uniquePtr1 = 10;
*uniquePtr2 = 20;
return 0;
}
推荐答案
但是,为什么这仍然有效
But still, why is this valid
它无效有效!这是不确定的行为,因为std::unique_ptr
的析构函数将释放具有自动存储持续时间的对象.
It is not valid! It's undefined behaviour, because the destructor of std::unique_ptr
will free an object with automatic storage duration.
实际上,您的程序尝试破坏int
对象三次.首先通过uniquePtr2
,然后通过uniquePtr1
,然后通过val
本身.
Practically, your program tries to destroy the int
object three times. First through uniquePtr2
, then through uniquePtr1
, and then through val
itself.
是否没有编译错误?
and not having a compilation error?
因为通常在编译时无法检测到此类错误:
Because such errors are not generally detectable at compile time:
unique_ptr <int> uniquePtr1(valPtr);
unique_ptr <int> uniquePtr2(function_with_runtime_input());
在此示例中,function_with_runtime_input()
可能执行许多复杂的运行时操作,最终会返回指向valPtr
所指向的同一对象的指针.
In this example, function_with_runtime_input()
may perform a lot of complicated runtime operations which eventually return a pointer to the same object valPtr
points to.
如果正确使用std::unique_ptr
,则几乎总是使用std::make_unique
,这样可以防止出现此类错误.
If you use std::unique_ptr
correctly, then you will almost always use std::make_unique
, which prevents such errors.
这篇关于C ++来自同一原始指针的多个唯一指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!