Tuesday Coding Tip 19 — [[nodiscard]] annotation

3 8 41
calendar_today agoschedule1 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 7 of 7 in Tuesday Coding Tips

1 Comment

0 votes
🔥 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

Tuesday Coding Tip 17 — Wrapping C APIs

Jakub Neruda - Jun 30

Tuesday Coding Tip 08 — Explicit template specialization

Jakub Neruda - Apr 21

Tuesday Coding Tip 05 - Object initialization in C++

Jakub Neruda - Mar 31
chevron_left
1.1k Points52 Badges
Brno, Czech Republiclinkedin.com/in/jakub-neruda
24Posts
13Comments
12Connections
Experienced C++ developer, team lead and hobby gamedev. I enjoy writing stuff about C++, clean code, clean architecture, and game development.

Related Jobs

View all jobs →

Commenters (This Week)

3 comments
1 comment
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!