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?

[[nodiscard]]を使って返り値を使うことを要求する

Last updated at Posted at 2025-06-03

[[nodiscard]]はC++17で追加された機能です

次のような関数があったとしましょう

add.cpp
int add(int a, int b)
{
    return a + b;
}

これを呼び出すときに

add(1,2)

のように呼び出すことはまずないでしょう。

足された結果を使わないと意味がないので、

int c = add(1,2)

とするわけです。

このような関数の特性をコンパイラに伝えるのに使うのが[[nodiscard]]です。(no discard = 破棄しない)
これは次のように使います:

add_revised.cpp
[[nodiscard]] int add(int a, int b)
{
    return a + b;
}

このように定義された関数を呼び出しておいて返り値を使わないと、コンパイラが警告を出します


add(1,2);  // コンパイラに警告される

int c = add(1,2);  // 期待されている呼び出し方

クラス一緒に使う

実はこの[[nodiscard]]、クラスのメンバ関数との相性が非常に良いのです。

pencil.hpp

class Pencil
{
    private:
    double m_length;
    
    
    public:
    
    Pencil(double length):m_length(length) {};
    ~Pencil() {}
    
    void use() { m_length -= 0.1; };
    
    [[nodiscard]] double getLength() const { return m_length; };
};

この例では、use()関数はクラスのメンバ変数を変更する役割を担っているのでこれに[[nodiscard]]は付きません。
一方、データを読み出すgetLength()関数はからの返り値は使わないと行けないので、[[nodiscard]]が付きます。

このようにして書くと、メンバ関数が変数に対して操作を行う関数なのか、変数を読み出す関数なのかがより分かりやすくなります。

メンバ関数定義で、クラスの中身の値は変更しない(=const関数)と返り値を使わないといけない(=[[nodiscard]])はほぼセットで出てくることを覚えておくと良いかもしれません。

参考文献

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?