Tuesday Coding Tip 19 — [[nodiscard]] annotation

●5 ●24 ●92
calendar_today • schedule1 min read
— Originally published at medium.com

Tuesday coding tips are super short posts about various tidbits mainly from C++, but also from other programming languages I use. You can also follow the #TuesdayCodingTips hashtag on Mastodon and Linkedin.


Since C++17, one can use [[nodiscard]] annotation to mark API functions whose return values should not be discarded without consideration. This usually applies to methods that make no sense to call without evaluating their return value (like predicate functions such as empty or a factory function). The compiler will issue a warning if the return value is not handled.

class [[nodiscard]] A {};

// OR

class B {
public:
    [[nodiscard]] B() = default;
};

// Enums can be nodiscard too
enum class [[nodiscard]] State {
    Default,
    Foo,
    Bar
};

int main()
{
    // warning: ignoring temporary created by a constructor declared with 'nodiscard' attribute
    A();
    B();
}

But beware! Sometimes it might be tempting to return some scope guard that will maintain postconditions automatically at the end of the scope using RAII (such as committing transactions). However, a user of your API can pipe the result of your nodiscard function into a std::ignore helper which causes the temporary to destruct immediately, defeating the idea of end-of-scope cleanup.

#include <tuple> // std::ignore

class [[nodiscard]] A {};
class B {
public:
    [[nodiscard]] bool isOk() const { return true; }
};

// no need for nodiscard, A is nodiscard
A foo() {
    return A();
}

// B is not nodiscard, mark it explicitly
[[nodiscard]] B bar() {
    return B();
}

int main()
{    
    foo(); // warning: ignoring temporary created by a constructor declared with 'nodiscard' attribute
    bar(); // warning

    std::ignore = foo(); // ok
    auto b = bar(); // ok
    b.isOk(); // warning
    if (b.isOk()) {} // ok
}
Part 19 of 31 in Tuesday Coding Tips
🔥 Join developers growing publicly
Share your knowledge, build in public, and grow your developer presence with a global community.

More Posts

Tuesday Coding Tip 06 - Explicit template instantiation

Jakub Neruda - Apr 7

Tuesday Coding Tip 02 - Template with type-specific API

Jakub Neruda - Mar 10

Let's play with C++ reflection

Jakub Neruda - Nov 12

Tuesday Coding Tip 17 — Wrapping C APIs

Jakub Neruda - Jun 30

Tuesday Coding Tip 31 — Deducing this

Jakub Neruda - Nov 17
chevron_left
2.1k Points • 121 Badges
Brno, Czech Republic • linkedin.com/in/jakub-neruda
42Posts
36Comments
22Connections
Experienced C++ developer, team lead and hobby gamedev. I enjoy writing stuff about C++, clean code, clean architecture, and game development.

Related Jobs

Commenters (This Week)

4 comments
1 comment
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!