vendredi 28 septembre 2018

Why overriding both the global new operator and the class spefic operator is not ambigous 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 ambigous 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)

Aucun commentaire:

Enregistrer un commentaire