Search code examples
c++c++11c++14language-lawyernew-operator

Why is overriding both the global new operator and the class-specific operator not ambiguous behaviour?


Consider the following code:

class Foo 
{
public:
    //class-specific
    Foo operator+(Foo& rhs)
    {
       return Foo(); //Just return a temporary
    }

    void* operator new(size_t sd)
    {
        return malloc(sd);
    }
};

//global
Foo operator+(Foo& lhs, Foo& rhs)
{
    return Foo();
}

void* operator new(size_t sd)
{
    return malloc(sd);
}

This code will not compile, stating the call is ambiguous because it matches two operators:

Foo a, b;
a + b;

But this one with the new operator compiles just fine, and will call the class-specific one.

Foo* a = new Foo();

Why doesn't it result in a compile error? Does the compiler treat the new operator differently? (Any citation to the standard would be appreciated.)


Solution

  • Why doesn't it result in a compile error? Does the compiler treat the new operator differently? (Any citation to the standard would be appreciated)

    Regarding the precedence between global new and class specific new, the reference says this:

    As described in allocation function, the C++ program may provide global and class-specific replacements for these functions. If the new-expression begins with the optional :: operator, as in ::new T or ::new T[n], class-specific replacements will be ignored (the function is looked up in global scope). Otherwise, if T is a class type, lookup begins in the class scope of T.

    So class specific new has priority.

    Regarding the overload of +, you can either have the member overload or the global overload (usually as a friend of the class) but not both because of the ambiguity it produces.