動的な生成と破棄

 

 

 

1. オブジェクトの動的な生成と破棄 (new/delete)

[概要]

オブジェクトを動的に生成するには、new 演算子を使用します。new 演算子は、オブジェクトを格納するメモリを確保し、初期化を行った後にそのメモリのアドレスを返します。メモリ確保に失敗した時は、std::bad_alloc 例外を送出します。

 

[環境]

コンパイラ : g++ 13.3.0
OS : Ubuntu-24.04 (WSL)  

 

new 演算子は、以下のように使用します。

int* p = new int;

 

値の初期化を一緒に行いたい場合、以下のように使用します。下記例は 10 で初期化しています。

int* p = new int(10);

 

new 演算子で配列を確保する場合は、以下のように使用します。

int* arr = new int[5];

 

配列の値を初期化と一緒に行いたい場合、以下のように使用します。下記例は {1,2,3,4,5} で初期化しています。

int* arr = new int[5]{1,2,3,4,5};

 

配列のサイズに 0 未満、もしくは実装で確保できる上限のサイズを超える値を指定すると、 std::bad_array_new_length 例外を送出します。

new 演算子でメモリを確保するとき std::nothrow を組み合わせると、メモリ確保に失敗した場合に例外を送出せず nullptr を返すようになります。

int* p = new(nothrow) int;

 

 

new 演算子で確保したメモリは、delete で開放する必要があります。

delete 演算子は、以下のように使用します。

delete p;

 

new[] 演算子で確保された配列を開放するには、delete[] 演算子を使用します。

delete[] p;

 

new / delete とメモリリーク

new 演算子で確保した領域は、delete による解放を忘れると メモリリーク という問題を発生します。この問題を防ぐ方法として、標準ライブラリが提供する unique_ptr や shared_ptr のようなスマートポインタ、vector などのコンテナ を積極的に使用することを強く推奨します。

 

 

上記内容を含む c++ プログラムを以下で紹介します。

 

ソースコード:

["new_delete_01.cpp"]

#include <iostream>     // for std::cout
#include <new>          // for std::nothrow, placement new
#include <memory>       // for std::make_unique

/**
 * @brief new/delete のシンプルなサンプル(構造体/クラスを使用しない)
 *
 * - 組み込み型(int)を使って `new` / `delete` / `new[]` / `delete[]` を示す
 * - `std::nothrow` と placement new の簡単な例を含む
 */

int main() {
    std::cout << "-- new/delete simple examples start --\n";

    // 1) 単一 int の new/delete
    {
        int* p = new int(10);
        std::cout << "*p = " << *p << "\n";
        delete p;
    }

    // 2) int 配列の new[] / delete[]
    {
        int* arr = new int[5]{1,2,3,4,5};
        for (int i = 0; i < 5; ++i) {
            std::cout << "arr[" << i << "] = " << arr[i] << "\n";
        }
        delete[] arr;
    }

    // 3) std::nothrow を使った例外を投げない new
    {
        int* p = new (std::nothrow) int(42);
        if (p) {
            std::cout << "nothrow allocated value = " << *p << "\n";
            delete p;
        } 
        else {
            std::cout << "nothrow allocation failed\n";
        }
    }

    // 4) placement new の例(int をバッファ上に構築)
    {
        alignas(int) unsigned char buffer[sizeof(int)];
        int* p = new (buffer) int(99); // placement new
        std::cout << "placement *p = " << *p << "\n";
        // int の破棄は特別な処理不要(ここでは何もしない)
    }

    // 5) std::unique_ptr (std::make_unique) と組み合わせた安全な管理
    {
        auto up = std::make_unique<int>(77);
        std::cout << "unique_ptr owns = " << *up << "\n";
    }

    // 6) std::unique_ptr (std::make_unique) の配列版(C++14 以降)
    {
        auto arr_up = std::make_unique<int[]>(5); // 要素はデフォルト初期化(ゼロでない場合あり)
        for (int i = 0; i < 5; ++i) {
            arr_up[i] = (i + 1) * 10;
        }
        std::cout << "make_unique<int[]> contents:";
        for (int i = 0; i < 5; ++i) {
            std::cout << ' ' << arr_up[i];
        }
        std::cout << '\n';
    }

    std::cout << "-- new/delete simple examples end --\n";
    return 0;
}

 

ビルドおよびプログラム実行例:

$ g++ -std=c++23 -Wall -Wextra -O2 new_delete_01.cpp -o new_delete_01.out && ./new_delete_01.out
-- new/delete simple examples start --
*p = 10
arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 4
arr[4] = 5
nothrow allocated value = 42
placement *p = 99
unique_ptr owns = 77
make_unique<int[]> contents: 10 20 30 40 50
-- new/delete simple examples end --
$

 

 

ライセンス

本ページの情報は、特記無い限り下記 MIT ライセンスで提供されます。

The MIT License (MIT)

  Copyright 2025 Kinoshita Hidetoshi

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

 

 

参考

 


 

変更履歴

2025-11-18 - 新規作成

 

Programming Items トップページ

プライバシーポリシー