C++•メモリ管理
C++ スマートポインタと RAII メモリ管理(C++11)
生の new と delete に別れを告げましょう。モダン C++ ではスマートポインタによって自動的かつ決定的にメモリを解放します。
構文
#include <memory>
auto ptr = std::make_unique<Type>(args);
auto shared = std::make_shared<Type>(args);
パラメータと値
この構文の主な構成要素と指定可能な値:
| パラメータ | 型 | 説明 |
|---|---|---|
| std::unique_ptr | Smart Pointer | オーバーヘッドなしの単独所有ポインタ。コピー不可、ムーブのみ可能。 |
| std::shared_ptr | Smart Pointer | 参照カウント付きの共有所有ポインタ。 |
そのまま実行できるコード例
Compilra で実行可能C++ をローカルにインストールせずに、この動作する完全なコード例を直接実行できます:
#include <iostream>
#include <memory>
#include <string>
class Resource {
public:
Resource() { std::cout << " [Resource] Allocated in heap memory.\n"; }
~Resource() { std::cout << " [Resource] Destructor called: freed automatically!\n"; }
void process() { std::cout << " [Resource] Processing work.\n"; }
};
int main() {
std::cout << "Entering scoped block:\n";
{
// Allocate unique_ptr using std::make_unique
std::unique_ptr<Resource> res = std::make_unique<Resource>();
res->process();
// Memory automatically freed when res exits scope
}
std::cout << "Exited scoped block cleanly (Zero memory leaks).\n";
return 0;
}期待される出力:
Entering scoped block: [Resource] Allocated in heap memory. [Resource] Processing work. [Resource] Destructor called: freed automatically! Exited scoped block cleanly (Zero memory leaks).
動作のしくみ: ステップ解説
- 5〜9行目: ライフサイクルを確認できるようコンストラクタとデストラクタを持つ Resource を定義します。
- 16〜18行目: std::make_unique でリソースを確保し、スコープ付きポインタに束縛します。
- 20行目: 閉じ括弧 } で delete なしにデストラクタが自動呼び出しされます。
重要ポイント
- RAII(Resource Acquisition Is Initialization)はリソースの寿命をオブジェクトのスコープに結びつけます。
- std::unique_ptr は生ポインタと比べて実行時オーバーヘッドがゼロです。
- スマートポインタを使う際に手動で delete を呼び出してはいけません。
よくある間違い: モダン C++ で生の new と delete を使うこと
手動の delete は、呼び出し前に例外が発生するとメモリリークにつながります。
❌ 誤り
Resource* r = new Resource(); // If an error happens here, r leaks! delete r;
✅ 正しい例
auto r = std::make_unique<Resource>(); // 100% leak-proof