Macro to replace C++ operator new

后端 未结 7 1804
臣服心动
臣服心动 2020-12-04 13:47

Is it possible to create macros to replace all forms of operator new with overloads that include additional args...say __FILE__ and __LINE__<

相关标签:
7条回答
  • 2020-12-04 14:20

    3.7.4 Dynamic storage duration

    2 The library provides default definitions for the global allocation and deallocation functions. Some global allocation and deallocation functions are replaceable (18.5.1). A C++ program shall provide at most one definition of a replaceable allocation or deallocation function. Any such function definition replaces the default version provided in the library (17.6.4.6) [...]

    17.6.4.6 Replacement functions

    1. A C++ program may provide the definition for any of eight dynamic memory allocation function signatures declared in header (3.7.4, Clause 18):

      • operator new(std::size_t)
      • operator new(std::size_t, const std::nothrow_t&)
      • operator new[](std::size_t)
      • operator new[](std::size_t, const std::nothrow_t&)
      • operator delete(void*)
      • operator delete(void*, const std::nothrow_t&)
      • operator delete[](void*)
      • operator delete[](void*, const std::nothrow_t&)

    Hope this clarifies what is a legal overload and what isn't.

    This may be of interest to a few here:

    #define delete cout <<  "delete called at: " << __LINE__ << " of " << __FILE__  << endl, delete 
    
    using namespace std;
    
    void *operator new(size_t size, ostream& o, char *f, unsigned l) {
        o << "new called at: " << l << " of " << f << endl;
        return ::new char[size];
    }
    
    int main() {
        int *a = new(cout, __FILE__, __LINE__) int;
        delete a;
    }
    

    Caveat Lector: What I do here is a Bad Thing (TM) to do -- overloading new/delete globally.

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