Why is there no std::allocate_unique function in C++14?

前端 未结 2 1110
感情败类
感情败类 2020-12-08 11:31

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 alloc

2条回答
  •  伪装坚强ぢ
    2020-12-08 11:49

    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).

提交回复
热议问题