目次
低レイヤーのプログラミングとOS開発が趣味。C言語を使っています。
工作HardwareHubからのお知らせ
サンプルコード
予め確保しておいたメモリ領域を 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
記事の執筆者にステッカーを贈る
有益な情報に対するお礼として、またはコメント欄における質問への返答に対するお礼として、 記事の読者は、執筆者に有料のステッカーを贈ることができます。
さらに詳しく →Feedbacks
ログインするとコメントを投稿できます。
関連記事
- ダウンキャスト (C++をもう一度)実行時型情報 RTTI #include <iostream> #include <typeinfo> using namespace std; class MyClass { public: virtual ~MyClass() {} // typeid で正しい RTTI // (RunTime Type Information; 実行時型情報) ...
- 競技プログラミングの基本処理チートシート (C++)限られた時間の中で問題を解くために必要となる、競技プログラミングにおける基本的な処理のチートシートです。競プロにおけるメジャー言語 C++ を利用します。その際 C++11 の機能は利用せず C++03 の機能の範囲内で記述します。 頻度高く定期的に開催されるコンテスト AtCoder Codeforces main.cpp #include <iostream>
- 構造体と列挙体 (C++をもう一度)構造体 #include <iostream> using namespace std; struct MyStruct { char charval; int intval; }; void Show(MyStruct* obj) { cout << obj->intval << endl; } int main() { ...
- Valgrind による C/C++ メモリリーク検出JVM メモリリークでは JDK の jstat や jmap で原因を調査できます。C/C++ では valgrind の Memcheck ツールが利用できます。valgrind には複数のツールが含まれており既定のツールが Memcheck です。他のツールを利用する場合は --tool オプションで指定します。 [簡単な利用例](h
- クラスの基本/初期化 (C++をもう一度)構造体のように初期化する (非推奨) #include <iostream> using namespace std; const int MAX_STR = 16; class MyClass { public: int m_integer; char m_str[MAX_STR + 1]; void Show(); }; void MyClass::Show...