【问题标题】:How to use new operator inside overloaded new operator?如何在重载的新运算符中使用新运算符?
【发布时间】:2015-04-12 17:14:18
【问题描述】:

我试图了解新的运算符重载,同时我对此深感困惑,我的问题是?

  1. 如何在全局和本地重载的 new 运算符中使用 new 运算符。

关于全局超载,我找到了这个链接 How do I call the original "operator new" if I have overloaded it?,但是我的本地重载 new 运算符呢?如果有人澄清我的问题,那对我来说也很有帮助。

除此之外,我还需要知道哪种方法是本地或全局重载新运算符的最佳方式(可能取决于我的设计),我还需要了解最佳设计和性能目的。感谢提前

【问题讨论】:

    标签: c++ operator-overloading new-operator


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      简单的答案。

      如果您想在全局和本地重载的 new 运算符中使用 new 运算符,则只需加上 :: 前缀(范围解析)即可寻址到全局 new 运算符。
      例如:operator new() -&gt; will call your custom local overloaded new operator.

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-03-13
        • 1970-01-01
        • 2019-10-16
        • 1970-01-01
        • 1970-01-01
        • 2012-11-18
        • 1970-01-01
        相关资源
        最近更新 更多