为什么在C ++ 14中没有std :: allocate_unique函数? [英] Why is there no std::allocate_unique function in C++14?

查看:254
本文介绍了为什么在C ++ 14中没有std :: allocate_unique函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 shared_ptr 有allocate_shared,而 unique_ptr 没有allocate_unique?
我想使用自己的分配器来创建一个unique_ptr:我必须自己分配缓冲区,然后将它分配给unique_ptr?

解决方案


为什么 shared_ptr allocate_shared ,而 unique_ptr 没有 allocate_unique


shared_ptr 需要使用分配器分配其内部共享状态(引用计数和删除程序)以及共享对象。 unique_ptr 只管理对象;因此不需要为 unique_ptr 本身提供一个分配器,并且不需要分配函数。



(同样的原因也不太需要 make_unique 在C ++ 11中的功能,但是为了一致性而被流行的需求添加到C ++ 14中。也许同样的需求会将 allocate_unique 添加到未来的标准。)


我必须自己分配缓冲区,然后将其分配给unique_ptr?


是的。或者你可以写自己的 allocate_unique ;不像 allocate_shared ,它可以,并且相当简单,分开实现它从 unique_ptr 本身。 (如在注释中提到的,你必须确保它为分配器使用了适当的删除器;默认的删除器将使用 delete 并且可怕的错误)。<


的确。



对于目前缺少 allocate_unique的更正式的理由, ,请参阅 <$ c $的提案c> make_unique ,特别是第4节(自定义删除)。


Why does shared_ptr have allocate_shared while unique_ptr does not have allocate_unique?
I would like to make a unique_ptr using my own allocator: do I have to allocate the buffer myself and then assign it to a unique_ptr?
This seems like an obvious idiom.

解决方案

Why does shared_ptr have allocate_shared while unique_ptr does not have allocate_unique?

shared_ptr needs it so that it can allocate its internal shared state (the reference count and deleter), as well as the shared object, using the allocator. unique_ptr only manages the object; so there is no need to provide an allocator to the unique_ptr itself, and less need for an allocate function.

(There is also less need for make_unique for the same reason, which is probably why it didn't feature in C++11, but was added to C++14 by popular demand for the sake of consistency. Maybe the same demand will add allocate_unique to a future standard.)

do I have to allocate the buffer myself and then assign it to a unique_ptr?

Yes. Or you could write your own allocate_unique; unlike allocate_shared, it's possible, and reasonably straightforward, to implement it separately from unique_ptr itself. (As mentioned in the comments, you'd have to make sure it used an appropriate deleter for the allocator; the default deleter would use delete and go horribly wrong).

This seems like an obvious idiom.

Indeed. But so are many other idioms, and not everything can (or should) be standardised.

For a more official justification of the current lack of allocate_unique, see the proposal for make_unique, specifically section 4 (Custom Deleters).

这篇关于为什么在C ++ 14中没有std :: allocate_unique函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆