C++ メモリ管理ライブラリ<new>

C++ は強力なプログラミング言語であり、開発者がより効率的にコードを書くのに役立つ豊富な標準ライブラリを提供しています。

C++ では、<new>非常に重要なヘッダーファイルであり、動的メモリ割り当てのための関数と例外型が含まれています。

動的メモリ割り当てにより、プログラムは実行時にメモリを要求できます。これはサイズが不定のデータ構造を扱う場合に非常に役立ちます。

<new>ヘッダーファイルには、以下の主要なコンポーネントが定義されています:

  • new演算子:動的メモリ割り当てに使用されます。
  • delete演算子:動的に割り当てられたメモリを解放するために使用されます。
  • nothrow演算子:メモリ割り当てが失敗したときに例外をスローしないために使用されます。
  • std::bad_alloc例外:メモリ割り当てが失敗したときにスローされます。

構文

使用new演算子

new演算子はヒープ上にメモリを割り当てるために使用します。基本的な構文は次のとおりです:

<code class="language-cpp">pointer new (type [, initializer]);</code>
  • pointerは割り当てられたメモリを指すポインタです。
  • typeは割り当てるオブジェクトの型です。
  • initializerはオプションの初期化式です。

使用delete演算子

delete演算子は、以前に使用したnew割り当てられたメモリを解放するために使用します。その基本的な構文は次のとおりです:

<code class="language-cpp">delete pointer;</code>
  • pointerは以前に使用したnew割り当てられたメモリへのポインタです。

例

単一オブジェクトの動的割り当て:

例

#include <iostream>
#include <new> // <new> ヘッダーファイルをインクルード

class MyClass {
public:
    int value;
    MyClass() : value(0) {}
};

int main() {
    MyClass* myObject = new MyClass; // MyClass オブジェクトを割り当てる
    myObject->value = 10; // ドット演算子を使用してメンバーにアクセス
    std::cout << "Value: " << myObject->value << std::endl;

    delete myObject; // メモリを解放
    return 0;
}

出力結果:

Value: 10

配列の動的割り当て:

例

#include <iostream>
#include <new>

int main() {
    int* myArray = new int[10]; // 10個の整数を含む配列を割り当てる
    for (int i = 0; i < 10; ++i) {
        myArray[i] = i * 2; // 配列を初期化
    }

    for (int i = 0; i < 10; ++i) {
        std::cout << "Array[" << i << "]: " << myArray[i] << std::endl;
    }

    delete[] myArray; // 配列のメモリを解放
    return 0;
}

出力結果:

Array[0]: 0
Array[1]: 2
Array[2]: 4
Array[3]: 6
Array[4]: 8
Array[5]: 10
Array[6]: 12
Array[7]: 14
Array[8]: 16
Array[9]: 18

nothrow を使用して例外を回避:

例

#include <iostream>
#include <new>

int main() {
    int* myArray = new(std::nothrow) int[10000000]; // 大きな配列を割り当てようとする
    if (!myArray) {
        std::cout << "Memory allocation failed." << std::endl;
    } else {
        std::cout << "Memory allocation succeeded." << std::endl;
        delete[] myArray; // メモリを解放
    }
    return 0;
}

出力結果:

Memory allocation failed. // 或者 Memory allocation succeeded. 取决于系统内存情况

例外処理

new 演算子でメモリ割り当てが失敗すると、C++ は std::bad_alloc 例外をスローします。

開発者は try-catch ブロックを使用してこの例外をキャッチし、処理できます。

例

#include <iostream>
#include <new>

int main() {
    try {
        int* myArray = new int[10000000]; // 大きな配列を割り当てようとする
        std::cout << "Memory allocation succeeded." << std::endl;
        delete[] myArray; // メモリを解放
    } catch (const std::bad_alloc& e) {
        std::cout << "Exception caught: " << e.what() << std::endl;
    }
    return 0;
}

出力結果:

Exception caught: std::bad_alloc // 如果内存分配失败
その他の拡張