问题描述
我们试图重载带有特定参数的delete []运算符。哪个是正确的方法调用它?我们使用GNU编译器并获取所有这些样本的编译器错误:
We're trying to overload the delete[] operator with specific arguments. Which is the right way to call it? We use the GNU compiler and obtain compiler errors with all of these samples:
#include<memory>
using namespace std;
typedef unsigned int P;
struct A{
static allocator<A>m;
P p;
void*operator new[](size_t s){return m.allocate(s);}
void operator delete[](void*p,int s){m.deallocate((A*)p,s);}
void operator delete[](void*p,size_t t,int s){m.deallocate((A*)p,s);}
};
int main(){
A*a=new A[10];
//delete (5) []a; //expected ',' before 'a'
//delete[5]a; //expected ';' before ']' token
//delete[] (5) a; //type ‘int’ argument given to ‘delete’, expected
//delete[]a (5); //a’ cannot be used as a function
//delete[]((int)5)a; //type ‘int’ argument given to ‘delete’, expected pointer
//delete[]a((int)5); //‘a’ cannot be used as a function
return 0;
}
推荐答案
对于这种放置删除器。
只有当位置为new的构造函数抛出异常时,才会调用放置删除器(与您声明的位置相同)。
然后程序将调用匹配的布置删除器(相同的签名),并尝试释放自定义分配的内存。
There's no "syntactic sugar" for this kind of placement deleter.
A placement deleter (like what you've declared) is only called when a constructor that was called by a placement new, throws an exception.
Then the program will call the matching placement deleter (same signature) and try to free the customly allocated memory.
如果您仍然想调用此方法,手动调用操作符:
If you still want to call this method, you'll have to call the operator manually:
A::operator delete[](a, 5);
这里有一个很好的例子:
There's a nice example of how it works here: http://en.cppreference.com/w/cpp/memory/new/operator_delete
请注意类析构函数中的异常(在触发异常后调用delete操作符):
Notice the exception in the class destructor (the delete operator is called after the exception is triggered):
#include <stdexcept>
#include <iostream>
struct X {
X() { throw std::runtime_error(""); }
// custom placement new
static void* operator new(std::size_t sz, bool b) {
std::cout << "custom placement new called, b = " << b << '\n';
return ::operator new(sz);
}
// custom placement delete
static void operator delete(void* ptr, bool b)
{
std::cout << "custom placement delete called, b = " << b << '\n';
::operator delete(ptr);
}
};
int main() {
try {
X* p1 = new (true) X;
} catch(const std::exception&) { }
}
这篇关于重载delete []具有特定参数的运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!