nagarajan
nagarajan

Reputation: 494

How to use new operator inside overloaded new operator?

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

Upvotes: 3

Views: 1437

Answers (2)

Shivaraj Bhat
Shivaraj Bhat

Reputation: 847

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.

Upvotes: 1

VolAnd
VolAnd

Reputation: 6407

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&) { }
}

Upvotes: 6

Related Questions