重载的 operator new
默认被认为是静态的吗?例如:
template <typename E>
class Link
{
private:
Link<E>* freeList;
public:
E element;
Link<E>* next;
Link(const E& elemVal, Link<E>* nextVal) { element = elemVal; next = nextVal; }
Link(Link<E>* nextVal) { next = nextVal; }
void* operator new(size_t)
{
Link<E>* temp=freeList;
freeList=freeList->next;
return temp;
}
};
当我尝试编译它时,出现以下错误:
Invalid use of member 'Link<E>::freeList' in static member function.
我想知道重载的 operator new
是否实际上是静态的。
最佳答案
是的!特定于类的 operator new
和 operator delete
的重载是静态成员函数。它们不能是“常规”成员函数,因为在调用它们时没有可用的实例。他们在那里(取消)分配原始存储。对于它们中的任何一个,此时都没有对象实例。
这在 [class.free]/1 中有描述:
Any allocation function for a class T is a static member (even if not explicitly declared static).
Any deallocation function for a class X is a static member (even if not explicitly declared static).
关于c++ - 是否有默认为静态的成员函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51581413/