c++重载operator new的练习
注意点1:
类中的operator new 和operator delete为static
遵循 访问限制
注意点2
operator delete 和operator new的第一个参数固定,通过第二个参数匹配new和delete
注意点3
operator delete,会在构造函数发生异常时自动调用
#include <stdexcept>
#include <iostream>
struct Ca
{
Ca(){
throw std::runtime_error("test");
}
//
void* operator new(size_t x, bool y) {
std::cout << "custom operator new\n" << y;
return ::operator new(x);
}
//构造函数发生异常,自动调用匹配的的delete函数
void operator delete(void* ptr, bool y) {
std::cout << "custom operator delete\n" << y;
::operator delete(ptr);
}
};
struct Cb
{
Cb(int a,int b,int c) try: a_(a),b_(b),c_(c) {
std::cout << "a_ is " << a_ << "b_ is " << b_ << "c_ is " << c_ << std::endl;;
throw std::runtime_error("test");
}
catch (std::exception& e) {
std::cout <<e.what()<< "Cb() try \n";
}
//
void* operator new(size_t x, bool y) {
std::cout << "custom operator new\n" << y;
return ::operator new(x);
}
//构造函数发生异常,自动调用匹配的的delete函数
void operator delete(void* ptr, bool y) {
std::cout << "custom operator delete\n" << y;
::operator delete(ptr);
}
int a_, b_, c_;
};
int main() {
try{
Ca *a = new(1)Ca;
}
catch (std::exception&e) {
std::cout << e.what() << "\n";
}
//要以这种方式才能捕获到,才会调用自定义的operator delete
try {
Cb *b = new(true)Cb{ 1,2,3 };
}
catch (std::exception&e) {
std::cout << e.what() << "\n";
}
}
//output
//custom operator new
//1custom operator delete
//1test
//custom operator new
//1a_ is 1b_ is 2c_ is 3
//testCb() try
//custom operator delete
//1test
浙公网安备 33010602011771号