【问题标题】:How to use new operator inside overloaded new operator?如何在重载的新运算符中使用新运算符?
【发布时间】:2015-04-12 17:14:18
【问题描述】:
【问题讨论】:
标签:
c++
operator-overloading
new-operator
【解决方案1】:
http://en.cppreference.com/w/cpp/memory/new/operator_new - 有例子和解释。
例如:
#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&) { }
}
【解决方案2】:
简单的答案。
如果您想在全局和本地重载的 new 运算符中使用 new 运算符,则只需加上 :: 前缀(范围解析)即可寻址到全局 new 运算符。
例如:operator new() -> will call your custom local overloaded new operator.
::operator new() -> will call global inbuilt new operator.