Skip to content

Latest commit

 

History

History
165 lines (125 loc) · 3.08 KB

293.md

File metadata and controls

165 lines (125 loc) · 3.08 KB
Info

Example

struct foo {
   [[nodiscard]] foo(auto& resource) {}
};

struct [[nodiscard]] bar {};

auto fn() -> bar;

[[nodiscard]] auto fn2() -> bool;

int main(int, char** argv){
    foo{argv}; // ignoring temp created by [[nodiscard]]
    fn();      // ignoring return value with [[nodiscard]]
    fn2();     // ignoring return value with [[nodiscard]]
}

https://godbolt.org/z/Mch6cGM1h

Puzzle

  • Can you mark all provided types/functions as [[nodiscard]] and handle the consequenes?

    • Do you know any production use cases when applying nodiscard for non-functions improves the code?
// TODO: mark nodiscard
struct foo { };
auto fn1() -> foo;
auto fn2() -> bool;

int main() {
    // TODO: handle nodiscard
    foo();
    fn1();
    fn2();
}

https://godbolt.org/z/coPPe4KTP

Solutions

struct [[nodiscard]] foo { };
[[nodiscard]] auto fn1() -> foo;
[[nodiscard]] auto fn2() -> bool;

int main() {
    (void)foo(); 
    (void)fn1();
    (void)fn2();
}

https://godbolt.org/z/h997hnKM4

struct [[nodiscard]] foo { };
[[nodiscard]] auto fn1() -> foo;
[[nodiscard]] auto fn2() -> bool;

int main() {
    std::ignore = foo();
    std::ignore = fn1();
    std::ignore = fn2();
}

https://godbolt.org/z/MjjM8fdrn

struct [[nodiscard]] foo { };
[[nodiscard]] auto fn1() -> foo;
[[nodiscard]] auto fn2() -> bool;

int main() {
    auto not_ignored = foo();
    auto not_ignored1 = fn1();
    auto not_ignored2 = fn2();
}

https://godbolt.org/z/sf9qPfj48

struct [[nodiscard]] foo { };
[[nodiscard]] auto fn1() -> foo;
[[nodiscard]] auto fn2() -> bool;

int main() {
  [[maybe_unused]] auto f = foo{};
  (void) fn1();
  ignore = fn2();
}

https://godbolt.org/z/eja8rc4sf

struct [[nodiscard]] foo {};
auto fn1() -> foo;
[[nodiscard]] auto fn2() -> bool;

int main() {
  std::ignore = foo();
  std::ignore = fn1();
  std::ignore = fn2();
}

https://godbolt.org/z/a73973Ge3

struct [[nodiscard]] foo { };      
[[nodiscard]] auto fn1() -> foo;
[[nodiscard]] auto fn2() -> bool;

int main() {
    static_cast<void>(foo());
    [[maybe_unused]] foo Ω = fn1();
    std::ignore = fn2();
}

https://godbolt.org/z/1WYx6WesG

struct [[nodiscard("Attribute 1")]] foo { };
[[nodiscard("Attribute 2")]] auto fn1() -> foo;
[[nodiscard("Attribute 3")]] auto fn2() -> bool;

int main() {
    // TODO: handle nodiscard
    static_cast<void>(foo());
    static_cast<void>(fn1());
    auto or_this = fn2();
}

https://godbolt.org/z/z5KTYG6s4

struct [[nodiscard]] foo {};
auto fn1() -> foo;
[[nodiscard]] auto fn2() -> bool;

int main() {
    // TODO: handle nodiscard
    static_cast<void>(foo());
    static_cast<void>(fn1());
    static_cast<void>(fn2());
}

https://godbolt.org/z/4c8rhq3W7