#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(){ }
我一直没有理解这个错误。
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.
我们在全局范围内隐式定义了分配函数,由库提供。有什么问题吗?我预计会应用重载决议。
我也想明白,使用这样的分配函数(具有三个参数)有什么意义。
最佳答案
正如引用所说,它只会在全局范围内查找分配函数如果在类的范围内查找未能找到名称。在您的情况下,它正在查找名称,因此不要在全局范围内查找它。唯一的问题是您的分配函数的参数数量与您调用它的方式不符。
如果要确保使用全局分配函数:
A *a = ::new A;
如果你想调用你定义的分配函数,你需要做:
A *a = new (someC, someOtherC) A;
关于c++ - 分配运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24721964/