c++ - 分配运算符重载

标签 c++ allocation

#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/

相关文章:

c++ - 这是系统资源吗? (或者我怎么知道我是否需要删除指针)- 在 C++ 中使用 C

c++ - 将 std::vector<bool> 传递给外部函数

链表中的连续动态内存分配

c - 未初始化的值是由堆分配创建的。为什么?

c++ - 为什么 C++11 删除的函数会参与重载决议?

c++ - 在 C 和 C++ 中的函数指针和对象指针之间转换

iphone - iPhone中的内存分配

ios - 如何在iOS中将NSObject分配到其自己的虚拟内存页面上?

c++ - 如何使用 C++ 分发 lua 文件

c - 已分配的内存 - 已分配数组的结构