Skip to content

[clang-tidy] Wrong modernize-use-nodiscard warning when function returns a type marked as [[nodiscard]] #163425

@fmun

Description

@fmun

clang-tidy 21.1.3 erroneously reports

warning: function '...' should be marked [[nodiscard]] [modernize-use-nodiscard]

even though the function's return type is a class marked with [[nodiscard]].

Example:

#include <optional>

template<typename T>
class [[nodiscard]] MayBe
{
public:
	MayBe() = default;
	MayBe(const T& t) : _value(t) {};
    [[nodiscard]] bool HasValue()const { return _value.has_value(); };
    [[nodiscard]] const auto& operator*()const { return *_value; };
private:
    std::optional<T> _value;
};

class X
{
public:
    MayBe<int> divide(int x, int y) const;
};

clang-tidy was called with -checks=modernize-use-nodiscard and returns this:

<source>:18:5: warning: function 'divide' should be marked [[nodiscard]] [modernize-use-nodiscard]
18 |     MayBe<int> divide(int x, int y) const;
   |     ^
   |     [[nodiscard]] 
  1 warning generated.

https://godbolt.org/z/xKhEbx5nY

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions