How do I call the original “operator new” if I have overloaded it?

后端 未结 1 1974
面向向阳花
面向向阳花 2020-11-29 06:20

Suppose I need to overload global ::operator new() for storing extra data with each allocated object. So basically it would work this way:

  • for eac
相关标签:
1条回答
  • 2020-11-29 06:56

    You can't access them because it isn't really overloading, it's replacement. When you define your own ::operator new, the old one goes away. That's pretty much that.

    Essentially, you need to call malloc from a custom ::operator new. Not only that, but also follow the directions in 18.4.1.1/4 to properly handle errors:

    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.

    0 讨论(0)
提交回复
热议问题