0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

new new ニュース!!

Posted at

C++のnewのエラー処理

news 速報
 最近くらいニュースばかりが続き、嫌になりますね。
日本人が108人くらい同時にノーベル賞とか受賞するとか、太陽みたいな宝石が見つかったとか、LLLED(LONG light LED)が開発されたとか。

 あ、そういう明るいではないか。

 今読んでいるあなたが、どんな時代でどんな環境にいるかは分かりませんが、明るく生きる秘訣を教えます。

 上を向いて生きることです。物理的に。
別に常にでは無いですが、特に辛い時にそうした方が良いと思います。

 何故なら太陽は上にあるから……(良いこと言った風)。

目次

  1. newとは
  2. newのエラー処理
  3. おわりに

1. newとは

 newはC++でメモリを動的に割り当てるために使われている演算子です。
C言語ではmallocで動的に確保しますが、C++ではnewを使います。

 そしてその型のコンストラクタを呼び出してオブジェクトを初期化します。

 つまり、mallocは動的確保だけですが、new はメモリ割り当てとオブジェクト構築の両方を行います。

使用例

int* myInt = new int(100);  // int型のオブジェクトを割り当て、100で初期化

2. newのエラー処理

 通常C言語のmallocではエラーだとNULLが返ってくるので、if文で見て、エラーをmainに返したり、exitしたりできます。

mallocのエラー処理の例

int* myInt = (int*)malloc(sizeof(int));
if (myInt == NULL)
{
    exit(1);
}

 しかし、newでは例外(std::bad_alloc)を投げます。
ですので、例外を投げずNULLを返すモードにするのか、例外をキャッチするのかを選ぶ必要があります。

例外を投げないnothrowモード

#include <iostream>
#include <new>

int* myInt = new(std::nothrow) int(100);
if (myInt == NULL)  // nullptrでも良い
{
    std::cerr << "Memory allocation failed." << std::endl;
    std::exit(1);
}

また、通常のエラー処理だと

try,catchモード

#include <iostream>
#include <new>

int* myInt;
try {
    myInt = new int(100); // ここでnothrowは使用しない
} catch (const std::bad_alloc& e) {
    std::cerr << "Memory allocation failed: " << e.what() << std::endl;
    std::exit(1);
}

と言う風になります。
どちらにするかはお好みで。

3. おわりに

 newのエラーはあまり起こりにくいと思いますが、こういったエラー処理を学ぶことで、他のエラー処理にも生きてくると思います。
 だれかの何かのお役に立てれば……。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?