除了分配内存和调用构造函数之外,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/