2

i am trying to understand about the new operator overloading, in mean while i got a deep confuse about that and my question over here is?

  1. How i can use new operator inside my overloaded new operator in both globally and locally.

Regarding global overload i found this link How do I call the original "operator new" if I have overloaded it?, but what about my local overloaded new operator. If any one give clarification about my question it will too help full for me.

Along with that i need to know which is the best way to overload new operator either locally or globally (may be its depends on my design) still i need to know for best design and performance purpose. Thank is advance

Community
  • 1
  • 1
nagarajan
  • 474
  • 3
  • 21

2 Answers2

6

http://en.cppreference.com/w/cpp/memory/new/operator_new - there are examples and explanetions.

E.g.:

#include <stdexcept>
#include <iostream>
struct X {
    X() { throw std::runtime_error(""); }
    // custom placement new
    static void* operator new(std::size_t sz, bool b) {
        std::cout << "custom placement new called, b = " << b << '\n';
        return ::operator new(sz);
    }
    // custom placement delete
    static void operator delete(void* ptr, bool b)
    {
        std::cout << "custom placement delete called, b = " << b << '\n';
        ::operator delete(ptr);
    }
};
int main() {
   try {
     X* p1 = new (true) X;
   } catch(const std::exception&) { }
}
VolAnd
  • 6,367
  • 3
  • 25
  • 43
0

Simple answer.

If you want to use new operator inside your overloaded new operator in both globally and locally, then just prefix with :: (scope resolution) to address to the global new operator.
Ex: operator new() -> will call your custom local overloaded new operator.

::operator new() -> will call global inbuilt new operator.
Shivaraj Bhat
  • 841
  • 2
  • 9
  • 20