gpt4 book ai didi

c++ - 是否有默认为静态的成员函数?

转载 作者:太空狗 更新时间:2023-10-29 20:08:53 27 4
gpt4 key购买 nike

重载的 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 newoperator delete 的重载是静态成员函数。它们不能是“常规”成员函数,因为在调用它们时没有可用的实例。他们在那里(取消)分配原始存储。对于它们中的任何一个,此时都没有对象实例。

这在 [class.free]/1 中有描述:

Any allocation function for a class T is a static member (even if not explicitly declared static).

[class.free]/5 :

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com