St.Antario
St.Antario

Reputation: 27385

Allocation operator overloading

#include <iostream>
#include <new>
#include <cstdlib>

using std::cout;

struct C{ };

struct A
{
    void* operator new(std::size_t, C*, C*){ A a; return &a; }
};

A *a= new A; //candidate function not viable: requires 3 arguments, but 1 was provided


int main(){ }

I haven't been understanding this error.

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.

We have implicitly defined allocation function in the global scope, provided by library. What's a problem? I expected that overload resolution will be applied.

I also would like to understand, what is the point of use such allocation function (with three parameters).

Upvotes: 0

Views: 69

Answers (1)

Joseph Mansfield
Joseph Mansfield

Reputation: 110658

As the quote says, it will only look up the allocation function in the global scope if looking it up in the class's scope fails to find the name. In your case, it is finding the name, so doesn't look it up in the global scope. The only problem is that your allocation function has the wrong number of arguments for the way you're calling it.

If you want to ensure the global allocation function is used:

A *a = ::new A;

If you want to call the allocation function you defined, you need to do:

A *a = new (someC, someOtherC) A;

Upvotes: 2

Related Questions