Search code examples
c++operator-overloadingnew-operator

Why new and delete operators signatures are different from all other operators


The signature for the new operator is:

void* operator new(size_t count)

There is a white space between the word "operator" and the word "new". This is:

  1. Different from all other operator signatures (besides new, delete and their array counterparts). for example:

    T& operator=(const T& other)

  2. Does not comply with function name rules of C++ which do not allow white spaces.

I assume that "operator" is a keyword in this case... But if this is correct, why isn't this the case in all other operator function signatures?

Is there an explanation for the inconsistency?


Solution

  • The C++ grammar is actually written in terms of tokens, which is consistent between all types of operator definitions. operators are special-purpose and fixed in terms of what tokens can follow after the operator keyword, but the whitespace that occurs is not mandated anywhere in the standard.

    As far as the C++ grammar is concerned, there is no difference between the following signatures:

    auto operator+=(const Foo&) -> Foo&
    auto operator +=(const Foo&) -> Foo&
    auto operator += (const Foo&) -> Foo&
    auto 
    operator
    +=
    (const Foo&) -> Foo&
    

    See example

    operator new is no more, or less, consistent here. The only deviation here is that some operators allow no space after the operator token, such as operator= -- and the reason for this is the way that tokens are broken up in the C++ grammar.

    Most tokens are alphanumeric sequences that break on special characters, such as whitespace or +,=, etc. In this case, operator= breaks into two tokens -- operator and =, which form the operator.

    This also follows that some operators are also compounds of multiple tokens, such as operator new[] -- which can also be written operator new [], since it is comprised of 3 tokens: operator, new, and [], as evident in the footnote from [over.oper.general]/1:

    [Note 1: The operators new[], delete[], (), and [] are formed from more than one token. The latter two operators are function call and subscripting. — end note]