c++ - 不调用放置释放函数

标签 c++ c++11 memory-management

我编写的以下代码必须同时调用放置释放和分配函数。

#include <iostream>
using namespace std;

struct A
{
    void * operator new [] (size_t t, int, int)
    {
        cout << "3 parameters allocation" << endl;
        return ::operator new[](t);
    }

    void operator delete [] (void *p, int, int)
    {
        cout << "3 parameters deallocation" << endl;
        return ::operator delete[](p);
    }
};

int main() 
{
    A *a = new (5,5) A[10]; //operator new [] (size_t, int, int) invoked
    delete [] a; //Error. Overload resolution is failed.
}

demo

5.3.4/22 说 N3797:

A declaration of a placement deallocation function matches the declaration of a placement allocation function if it has the same number of parameters and, after parameter transformations (8.3.5), all parameter types except the first are identical. If the lookup finds a single matching deallocation function, that function will be called; otherwise, no deallocation function will be called.

它不是在C++11中实现的还是我的误解?

最佳答案

如果提供了特定于类的释放函数,则没有以范围解析运算符为前缀的delete-expression 是非良构的,除非具有一个或两个参数的特定于类的释放函数是可用:

10 - If the type is complete and if deallocation function lookup finds both a usual deallocation function with only a pointer parameter and a usual deallocation function with both a pointer parameter and a size parameter, then the selected deallocation function shall be the one with two parameters. Otherwise, the selected deallocation function shall be the function with one parameter.

所以你需要:

  • 提供 void operator delete[](void*);,
  • 提供void operator delete[](void*, size_t);,或者
  • 编写::delete[]一个

关于c++ - 不调用放置释放函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25019041/

相关文章:

c++ - 类函数与非类函数的名称冲突

php - Facebook HipHop (PHP to C++) 能否在Windows上编译运行

c++ - 为什么只有 char* 是 <Bad Ptr>,而不是其他数据类型?

c++ - 未在可变函数模板中推导出上下文

python - 什么时候不应该在 Python 中使用 self 约定?

java - JVM内存管理和垃圾收集书?

c++ - 如何从 std vector 前面读取并删除读取变量?

C++ 原子对象无锁保证

c++ - 如何使用 Boost 实现 C++14 风格的自动返回类型?

JavaScript 新关键字和内存管理