C ++ STL分配器vs运算符new [英] C++ STL allocator vs operator new

查看:91
本文介绍了C ++ STL分配器vs运算符new的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据C ++ Primer第4版,第755页,有一条注释说:

According to C++ Primer 4th edition, page 755, there is a note saying:

现代C ++程序通常应使用分配器类 分配内存.更安全,更灵活.

Modern C++ programs ordinarily ought to use the allocator class to allocate memory. It is safer and more flexible.

我不太明白这句话. 到目前为止,我阅读的所有材料都使用new教书以C ++分配内存. 本书展示了向量类如何利用分配器的一个示例. 但是,我想不出其他情况.

I don't quite understand this statement. So far all the materials I read teach using new to allocate memory in C++. An example of how vector class utilize allocator is shown in the book. However, I cannot think of other scenarios.

任何人都可以帮助澄清这一说法吗?再给我更多例子吗? 什么时候应该使用分配器,什么时候应该使用new?谢谢!

Can anyone help to clarify this statement? and give me more examples? When should I use allocator and when to use new? Thanks!

推荐答案

对于常规编程,是的,您应该使用newdelete.

For general programming, yes you should use new and delete.

但是,如果您正在编写库,则不应该! 我没有您的教科书,但我想它正在编写库代码的背景下讨论分配器.

However, if you are writing a library, you should not! I don't have your textbook, but I imagine it is discussing allocators in the context of writing library code.

图书馆的用户可能希望完全控制从何处分配的内容.如果库的所有分配都通过newdelete,则用户将无法获得这种细粒度的控制级别.

Users of a library may want control over exactly what gets allocated from where. If all of the library's allocations went through new and delete, the user would have no way to have that fine-grained level of control.

所有STL容器都带有一个可选的分配器模板参数.然后,容器将使用该分配器来满足其内部内存需求.默认情况下,如果省略分配器,它将使用 std::allocator 使用newdelete(特别是::operator new(size_t)::operator delete(void*)).

All STL containers take an optional allocator template argument. The container will then use that allocator for its internal memory needs. By default, if you omit the allocator, it will use std::allocator which uses new and delete (specifically, ::operator new(size_t) and ::operator delete(void*)).

这样,该容器的用户可以根据需要控制从哪里分配内存.

This way, the user of that container can control where memory gets allocated from if they desire.

实现与STL一起使用的自定义分配器的示例及其说明:使用STL的自定义池分配器提高性能

Example of implementing a custom allocator for use with STL, and explanation: Improving Performance with Custom Pool Allocators for STL

侧面说明:分配器的STL方法在几种方面都不理想.我建议阅读建立更好的分配器模型讨论其中一些问题.

Side Note: The STL approach to allocators is non-optimal in several ways. I recommend reading Towards a Better Allocator Model for a discussion of some of those issues.

2019年自编写此答案以来,C ++的情况已有所改善.有状态分配器受支持在C ++ 11中,而该支持在C ++ 17中得到了改进.那些涉及迈向更好的分配器模型"的人参与了这些更改(例如:

Edit in 2019: The situation in C++ has improved since this answer was written. Stateful allocators are supported in C++11, and that support was improved in C++17. Some of the people involved in the "Towards a Better Allocator Model" were involved in those changes (eg: N2387), so that's nice (:

这篇关于C ++ STL分配器vs运算符new的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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