サンプルコード
予め確保しておいたメモリ領域を new で指定してオブジェクトを生成できます。この場合の new を placement new とよびます。
#include <iostream>
using namespace std;
class MyClass {
public:
MyClass() {
cout << "MyClass" << endl;
}
~MyClass() {
cout << "~MyClass" << endl;
}
public:
void Say() {
cout << "Say" << endl;
}
};
const int SIZE = 2;
char* reserved = new char[SIZE * sizeof(MyClass)];
MyClass& GetAt(size_t i) {
return reinterpret_cast<MyClass&>(reserved[i * sizeof(MyClass)]);
}
int main() {
for (int i = 0; i < SIZE; ++i) {
new(&GetAt(i)) MyClass(); // placement new
}
for (int i = 0; i < SIZE; ++i) {
GetAt(i).Say();
}
for (int i = 0; i < SIZE; ++i) {
GetAt(i).~MyClass();
}
delete[] reserved;
return 0;
}
0
低レイヤーのプログラミングとOS開発が趣味。C言語を使っています。
記事の執筆者にステッカーを贈る
有益な情報に対するお礼として、またはコメント欄における質問への返答に対するお礼として、 記事の読者は、執筆者に有料のステッカーを贈ることができます。
さらに詳しく →Feedbacks
ログインするとコメントを投稿できます。


