2015-02-12 91 views
1

我想了解新的操作符重載,意思是說當我對此有深刻的疑惑時,我的問題在這裏是?如何在重載的新操作符中使用new操作符?

  1. 如何我可以在全局和本地重載的新運算符中使用new運算符。

關於全局超載,我發現這個鏈接 How do I call the original "operator new" if I have overloaded it?,但我本地重載的新操作符呢?如果有人對我的問題給予澄清,它對我來說也會有幫助。除此之外,我還需要知道哪些是在本地或全球範圍內重載新操作員的最佳方式(可能取決於我的設計),但仍需要了解最佳設計和性能目的。感謝提前

回答

4

http://en.cppreference.com/w/cpp/memory/new/operator_new - 有例子和解釋。

例如爲:

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

簡單的答案。

如果您想要在全局和本地重載的新運營商內部使用新的運營商,那麼只需前綴::(範圍分辨率)即可解決全球新運營商的問題。
例如:operator new() -> will call your custom local overloaded new operator.

::operator new() -> will call global inbuilt new operator.