What's the advantage of using std::allocator instead of new in C++?

前端 未结 8 1968
天命终不由人
天命终不由人 2020-12-04 13:14

I\'ve just read about std::allocator. In my opinion, it is more complicated to use it instead of using new and delete.

With <

8条回答
  •  感情败类
    2020-12-04 13:21

    std::allocator is the default memory allocator for the standard library containers, and you can substitute your own allocators. This allows you to control how the standard containers allocate memory. But I don't think that your question is about std::allocator specifically, but rather the strategy of allocating memory, then constucting objects in that memory, rather than using new T[N], for example.

    And the reason for that is that new T[N] doesn't allow you control over what constructors are called. And it forces you to construct all your objects at the same time. This is terrible for the purposes of, for example, std::vector where you only want to allocate occasionally.

    With a raw memory allocator, you can allocate a certain amount of memory, which determines your capacity. Then, as the user adds items to the vector (using the constructor of their choice), you can construct objects in place in this memory.

    Then when you run out of memory, you allocate more, typically twice as much. If std::vector used new T[N], it would have to reallocate every time you wanted to add or remove an element, which would be terrible for performance. You would also be forced to use the default constructor for all the objects, which puts an unnecessary restriction on the types of objects std::vector can hold.

提交回复
热议问题