简体   繁体   English

是否存在默认静态的成员函数?

[英]Are there member functions which are static by default?

Is an overloaded operator new considered static by default? 重载operator new是否默认为静态? For example: 例如:

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;
    }
};

When I tried to compile it, I got the following error: 当我尝试编译它时,我收到以下错误:

Invalid use of member 'Link<E>::freeList' in static member function.

I wonder if the overloaded operator new is actually static. 我想知道重载的operator new是否实际上是静态的。

Yes! 是! The overloads for class specific operator new and operator delete are static member functions. 类特定operator newoperator delete的重载是静态成员函数。 They can't be "regular" member functions since there is no instance available at the point of calling them. 它们不能是“常规”成员函数,因为在调用它们时没有可用的实例。 They are there to (de)allocate raw storage. 他们在那里(de)分配原始存储。 There is no object instance at that point, for either of them. 此时没有对象实例,对于它们中的任何一个。

This is described in [class.free]/1 : 这在[class.free] / 1中有描述:

Any allocation function for a class T is a static member (even if not explicitly declared static). 类T的任何分配函数都是静态成员(即使未明确声明为static)。

And [class.free]/5 : 并且[class.free] / 5

Any deallocation function for a class X is a static member (even if not explicitly declared static). 类X的任何释放函数都是静态成员(即使未明确声明为静态成员)。

Yes, the static keyword is optional for operator new , when it's defined as member function of a class it'll always be static member function. 是的, static关键字对于operator new是可选的,当它被定义为类的成员函数时,它将永远是static成员函数。

(emphasis mine) (强调我的)

Both single-object and array allocation functions may be defined as public static member functions of a class (versions (15-18)). 单对象和数组分配函数都可以定义为类的公共静态成员函数(版本(15-18))。 If defined, these allocation functions are called by new-expressions to allocate memory for single objects and arrays of this class, unless the new expression used the form ::new which bypasses class-scope lookup. 如果已定义,则new-expression将调用这些分配函数,以便为单个对象和此类的数组分配内存,除非新表达式使用了形式:: new来绕过类范围查找。 The keyword static is optional for these functions: whether used or not, the allocation function is a static member function. 关键字static对于这些函数是可选的:无论是否使用,分配函数都是静态成员函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM