重载operator new()还用其他两个不常见的用途
1 我们也许会想在内存的指定位置上放置一个对象。这对于面向硬件的内嵌系统特别重要,
在这个系统中,一个对象可能和一个特定的硬件是同义的
2 也许会想转在调用new时,能够选择不同的内存分配方案了
这两个特性可以用相同的机制实现:重载的operator new()可以带一个或多个
参数。
最初在调用过程中传递额外的参数给operator new()的方法看起来似乎有点
古怪:在关键字new后是参数表,参数表后面市正在创建的对象的类名字
在一个特定的存储单元里放置一个对象
//: C13:PlacementOperatorNew.cpp
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
// Placement with operator new()
#include <cstddef> // Size_t
#include <iostream>
using namespace std;
class X {
int i;
public:
X(int ii = 0) : i(ii) {
cout << "this = " << this << endl;
}
~X() {
cout << "X::~X(): " << this << endl;
}
void* operator new(size_t, void* loc) {
return loc;
}
};
int main() {
int l[10];
cout << "l = " << l << endl;
X* xp = new(l) X(47); // X at location l
xp->X::~X(); // Explicit destructor call
// ONLY use with placement!
getchar();
} ///:~
operator new()仅返回了传递给他的指针。因此,调用者可以决定就对象存放
在哪里,这时在该指针所指向的那块内存上,作为new表达式一部分的构造函数
将被调用
在销毁对象时会出现两难选择的局面。因为仅有一个版本的operator delete,
所以没有办法说“对这个对象使用我特殊内存释放器”
输出
l = 0073FAC4
this = 0073FAC4
X::~X(): 0073FAC4