c++ - 除了分配和 ctor 调用之外,C++ new 运算符还做什么?

标签 c++ new-operator

除了分配内存和调用构造函数之外,new 运算符还做了哪些其他事情?

最佳答案

C++ 标准对来自 <new> 的 new 运算符的单个对象形式(通常使用的形式)有这样的说法。 header :

Required behavior:

Return a nonnull pointer to suitably aligned storage (3.7.3), or else throw a bad_alloc exception. This requirement is binding on a replacement version of this function.

Default behavior:

— Executes a loop: Within the loop, the function first attempts to allocate the requested storage. Whether the attempt involves a call to the Standard C library function malloc is unspecified.

— Returns a pointer to the allocated storage if the attempt is successful. Otherwise, if the last argument to set_new_handler() was a null pointer, throw bad_alloc.

— Otherwise, the function calls the current new_handler (18.4.2.2). If the called function returns, the loop repeats.

— The loop terminates when an attempt to allocate the requested storage is successful or when a called new_handler function does not return.

该标准还有很多关于新运算符和动态内存分配的其他内容(要说的太多了),但我认为“默认行为”列表很好地总结了新运算符的基础知识。

关于c++ - 除了分配和 ctor 调用之外,C++ new 运算符还做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/377178/

相关文章:

C++:为什么 VS2005 中的(模板)类中的运算符放置 new 不被识别为内联友元函数?

c++ - for() 和 while() 之间有什么性能差异吗?

c++ - 将索引数组排序为主数组

C++ - 在调试期间无法使用 'new' 运算符

c# - 注册对象创建事件

c# - C# 中的新运算符不会覆盖基类成员

c++ - make_shared 与自定义新运算符

c++ - QT 使用 QGraphics 在一条直线上绘制椭圆或三角形

c++ - 机器相关指针值的混淆

C++正则表达式错误