在派生 class 中重载新运算符

Overloading new operator in the derived class

我在 Base class 中重载了 new 运算符。但是,当我向 Derived class 添加额外的重载 new 时,gcc 编译器在 Base class 中找不到 new 运算符。为什么?

最好的, 亚历克斯

#include <stdlib.h>
template <class t> class Base {
  public:
    Base() {}
    void * operator new (size_t size, void *loc) { return loc; }
};

template <class t> class Derived : public Base<t> {
  public:
    Derived() {}
    void * operator new (size_t size, int sz, void *loc) { return loc; }

};

void foo() {
  void *loc = malloc(sizeof(Derived<char>));
  Derived<char> *d = new (loc) Derived<char>();
}

gcc 输出:

   new.cpp: In function ‘void foo()’:
new.cpp:17:45: error: no matching function for call to ‘Derived<char>::operator new(sizetype, void*&)’
  Derived<char> *d = new (loc) Derived<char>();
                                             ^
new.cpp:17:45: note: candidate is:
new.cpp:11:10: note: static void* Derived<t>::operator new(size_t, int, void*) [with t = char; size_t = unsigned int]
   void * operator new (size_t size, int sz, void *loc) { return loc; }
          ^
new.cpp:11:10: note:   candidate expects 3 arguments, 2 provided

当您通过放置 new 表达式调用 operator new

new (loc) Derived<char>();

编译器在 Derived class 中查找 operator new 的重载(而不是 Base class)。它找到了,但是你的超载

void * operator new (size_t size, int sz, void *loc) { return loc; }
//                                ^ additional parameter

接受更多参数,因此出现错误。

如果你问为什么编译器不够聪明,无法调用 Baseoperator new 重载,那是因为 name hidingoperator new 重载在 Derived class 中隐藏了 Base class 之一。如果你想让 Base::operator new 重载在你的 Derived class 中可见,请使用

using Base<t>::operator new;