我编写的以下代码必须同时调用放置释放和分配函数。
#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.
}
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/