「nullptr」の版間の差分

提供: C++入門
移動: 案内検索
(ページの作成:「nullptr とは、C++でNULLを扱ったときに、関数のオーバーロードなどで予期しない動作をしたため、C++11で導入された[[NU...」)
(相違点なし)

2014年1月2日 (木) 22:55時点における版

nullptr とは、C++でNULLを扱ったときに、関数のオーバーロードなどで予期しない動作をしたため、C++11で導入されたNULLの代わりです。

読み方

nullptr
ぬる ぴーてぃーあーる、ぬるぽいんたー

概要

NULLの定義が0や0Lとされていたため、オーバーロードのときにf(int)やf(double*)の評価で期待した結果が得られていませんでした。

std::nulptr_tという型も定義されました。

NULLとnullptr

従来のC++

従来のC++では、NULLをこのように使用していました。

int *p = NULL;

C++11

C++11からは、ポインタの初期化時にNULLを代入するなら、nullptrを代入します。

int *p = nullptr;

NULLで期待した動作をしない例

ソースコード null.cpp

#include <iostream>
using namespace std;
void f(double *fptr) {
        cout << __PRETTY_FUNCTION__ << endl;
}
void f(int i) {
        cout << __PRETTY_FUNCTION__ << endl;
}
int main(int argc, char const* argv[])
{
        f(0);           // f(int)
        f(NULL);        //f(double*)を呼び出さず、f(int)になってしまう。
        return 0;
}

コンパイル

g++  null.cpp -o null

実行例

これがNULLが0である弊害です。

% ./null
void f(int)
void f(int)

nullptrの使用例

ソースコード nullptr1.cpp

#include <iostream>
using namespace std;
void f(double *fptr) {
        cout << __PRETTY_FUNCTION__ << endl;
}
void f(int i) {
        cout << __PRETTY_FUNCTION__ << endl;
}
int main(int argc, char const* argv[])
{
        f(0);           // f(int)
        f(nullptr);     //f(double*)
 
        {
                char *null_ptr = NULL;
                char *nullptr_ptr = nullptr;
                if (null_ptr == nullptr_ptr) {
                }
        }
        return 0;
}

コンパイル

g++49 -std=c++11 -I/usr/local/lib/gcc49/include/c++/ \
-Wl,-rpath=/usr/local/lib/gcc49  -pthread nullptr1.cpp -o nullptr1

実行例

% ./nullptr1
void f(int)
void f(double*)

nullptr_tの使用例

ソースコード nullptr_t1.cpp

#include <iostream>
using namespace std;
void f(double *fptr) {
        cout << __PRETTY_FUNCTION__ << endl;
}
void f(int i) {
        cout << __PRETTY_FUNCTION__ << endl;
}
void f(std::nullptr_t np) {
        cout << __PRETTY_FUNCTION__ << endl;
}
int main(int argc, char const* argv[])
{
        f(0);           // f(int)
        f(nullptr);     // f(nullptr_t)
        return 0;
}

コンパイル

g++49 -std=c++11 -I/usr/local/lib/gcc49/include/c++/ \
-Wl,-rpath=/usr/local/lib/gcc49  -pthread nullptr_t1.cpp -o nullptr_t1

実行例

% ./nullptr_t1
void f(int)
void f(std::nullptr_t)

関連項目