Help us understand the problem. What is going on with this article?

ポインタのヌル確認(C++)

結論

ヌル確認は、ポインタ単体をif文に入れるだけでOK。

サンプルコード

生ポインタ

sample_rawptr.cpp
#include <iostream>

int main()
{

    int* ptr1 = new int(0);
    int* ptr2{};

    if (ptr1)
    {
        std::cout << "ptr1 is not null" << std::endl;
    } // 生ポインタがヌルポインタでない

    if (!ptr2)
    {
        std::cout << "ptr2 is null" << std::endl;
    } // 生ポインタがヌルポインタである

    return 0;

}

スマートポインタ

sample_smartptr.cpp
#include <memory>
#include <iostream>

int main()
{
    std::shared_ptr<int> ptr1(new int(0));
    std::shared_ptr<int> ptr2;

    if (ptr1)
    {
        std::cout << "ptr1 is not null" << std::endl;
    } // スマートポインタがリソースを指し示している

    if (!ptr2)
    {
        std::cout << "ptr2 is null" << std::endl;
    } // スマートポインタがリソースを指し示していない
    return 0;

}

実行結果

sample_rawptr.cpp
ptr1 is not null
ptr2 is null
sample_smartptr.cpp
ptr1 is not null
ptr2 is null

解説

生ポインタ

生ポインタがnullの場合0が入る。C++のif文では0をfalse、それ以外をtrueとするため。

スマートポインタ

operator bool なるものが実装されているらしく、
ポインタが何らかのリソースを指しているときtrue, そうでないときfalseとなるらしい。

[参考URL]
https://cpprefjp.github.io/reference/memory/shared_ptr/op_bool.html

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away