本文介绍了为什么 unique_ptr<T>不能从 T* 构建?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是错误"用这段代码,举个简单的例子?

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&lt;T&gt;不能从 T* 构建?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 02:44