Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
252 views
in Technique[技术] by (71.8m points)

c++ - Why overloaded new operator is implicitly static and no scope resolution required to construct the object

Why overloaded new operator is implicitly static and how we are able to allocate memory by calling overloaded new operator without scope resolution operator?

In my view if something is static then we can call it in main by through class name.

class xyz
{
    void* operator new (size_t size); //implicitly declared static
    void operator delete (void *p); //implicitly declared static
};

int main()
{
    C *p = new C;
    delete p;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The draft C++ standard says in section 5.3.4 New paragraph 9 that if the new expression does not begin with :: then it is looked up in the scope of they type first and then if not found globally:

If the new-expression begins with a unary :: operator, the allocation function’s name is looked up in the global scope. Otherwise, if the allocated type is a class type T or array thereof, the allocation function’s name is looked up in the scope of T. If this lookup fails to find the name, or if the allocated type is not a class type, the allocation function’s name is looked up in the global scope

As to why it is implicitly static, it seems like it would be inconvenient restriction to require an instance of the type in order to invoke the member allocation function. It seems like would also require different syntax since how would the compiler know which instance to use which would make things messy.

The fact that member allocation functions are implicitly static is covered in section 12.5 Free store:

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...