问题描述
什么是错误"用这段代码,举个简单的例子?
What's "wrong" with this code, for a simple-minded example?
unique_ptr<char> meow = strdup("meow");
我是否提供删除器"unique_ptr
模板的参数,不能从 T*
分配 unique_ptr
.
Whether or not I provide the "deleter" argument to the unique_ptr
template, a unique_ptr<T>
cannot be assigned from T*
.
为什么 不提供这种看似直观的快捷方式?这只是一个疏忽,还是出于某种原因,这种可分配性是一个根本坏主意?
Why wouldn't <memory>
offer this seemingly intuitive shortcut? Is it simply an oversight, or would such assignability be a fundamentally bad idea for some reason?
推荐答案
想象一下你有
int bar;
{
int * foo = &bar;
std::unique_ptr<int> uptr = foo;
// use uptr
}
当 uptr
超出范围时,它会尝试执行 delete pointer;
,它会尝试在内存上调用 delete
不是由 new
分配的.这是未定义的行为,可能会导致各种问题.标准不允许编写此类有缺陷的代码,而是不允许这样做.
When uptr
goes out of scope, it's going to try and do delete pointer;
, which will try to call delete
on memory that was not allocated by new
. That's undefined behavior and can cause all sorts of problems. Instead of allowing buggy code like that to be able to be written, the standard disallows it.
如果你真的确定要从现有指针构造一个unique_ptr
,并且你知道默认删除器就是你想要的,那么你可以使用
If you are really sure you want to construct a unique_ptr
from an existing pointer, and you know the default deleter is what you want, then you can use the form of
auto pointer_name = std::unique_ptr<type>(pointer_i_know_needs_to_be_deleted);
这篇关于为什么 unique_ptr<T>不能从 T* 构建?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!