備忘録と戯言

学生がプログラミングの備忘録となんか印象に残ったことを綴る

NULLとnullptrの違い

今回はNULLとnullptrについて調べてみました。

「NULL」と「nullptr」はポインタに格納されている値が「何もない」とか「空である」といった意味を示すキーワードですが、どのような違いがあるのかを調べてみました。

   int* p = NULL;
   int* q = nullptr;


以下のコードを書きました。

 #include <iostream>

 void function(int)
 {
     std::cout << "function with arguments of int was called" << std::endl;
 }

 void function(int*)
 {
     std::cout << "function with arguments of int pointer was called" << std::endl;
 }

 int main()
 {
     function(10);
     function(true);

     function(NULL);
     function(nullptr);

     return 0;
 }

関数のオーバーロードを使い、それぞれがどの関数を呼ぶかを検証しました。

結果

function with arguments of int was called
function with arguments of int was called
function with arguments of int was called
function with arguments of int pointer was called
続行するには何かキーを押してください . . .

nullptr以外は、int型を引数に持つ関数が呼ばれました。

10 , trueは置いておいて、「NULL」と「nullptr」で違いがでました。

ポインタを「空」であると示していたNULLがなぜポインタ側の関数を呼ばないのか・・・

ご存知のとおり、NULL は以下のようにマクロで定義されているのです。

#define NULL    0

NULLと言われても所詮は「0」なのです。

なのでNULLはint型の引数を持つ関数を呼んでしまうのです。

NULLを使うときの落とし穴の1つで、このことを知らないと、関数のオーバーロードで意図した関数を呼び出せなくて実行結果がおかしくなることかあるかもしれません。

私は詳しくないのですが「nullptr」はC++11から新しく出たキーワードだそうです。
(私は講師に「こんなのがあるよ」程度しか教わっていませんでした。)


ここで、気になるのが、nullptrは何型なのか?ということ。

調べてみるとnullptrはstd::nullptr_t型であると記載されていました。


ここでまた、検証してみました。

上のコードに少し付け足ししました。

 #include <iostream>

 void function(int)
 {
     std::cout << "function with arguments of int was called" << std::endl;
 }

 void function(int*)
 {
     std::cout << "function with arguments of int pointer was called" << std::endl;
 }

 void function(std::nullptr_t)
 {
     std::cout << "function with arguments of std::nullptr_t was called" << std::endl;
 }

 int main()
 {
     function(NULL);
     function((int*)NULL);

     function(nullptr);

     return 0;
 }

結果

function with arguments of int was called
function with arguments of int pointer was called
function with arguments of std::nullptr_t was called
続行するには何かキーを押してください . . .

これで、nullptrはstd::nullptr_t型であることが証明されました。


NULLにはもっと深い歴史がある?かはわかりませんが、私の教わった事と調べた事を綴りました。

何か付加情報などがあれば教えてください。

NULLとnullptrの(大雑把な(保険))違いでした。

ではこれで。