From 23e7b35c39810ddf308961222637461984602c46 Mon Sep 17 00:00:00 2001 From: Tulio Leao Date: Wed, 19 Jun 2019 12:23:45 -0300 Subject: [PATCH] Add section about C++17 attributes (#50) * Add section about C++17 attributes Explains, in a single piece of code, about [[nodiscard]], [[fallthrough]] and [[maybe_unused]] --- CPP17.md | 20 ++++++++++++++++++++ README.md | 21 +++++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/CPP17.md b/CPP17.md index adbc43a..7f3b0bd 100644 --- a/CPP17.md +++ b/CPP17.md @@ -17,6 +17,7 @@ C++17 includes the following new language features: - [constexpr if](#constexpr-if) - [utf-8 character literals](#utf-8-character-literals) - [direct-list-initialization of enums](#direct-list-initialization-of-enums) +- [New standard attributes](#new-standard-attributes) C++17 includes the following new library features: - [std::variant](#stdvariant) @@ -237,6 +238,25 @@ byte d = byte{1}; // OK byte e = byte{256}; // ERROR ``` +### New standard attributes +C++17 introduces three new attributes: `[[fallthrough]]`, `[[nodiscard]]` and `[[maybe_unused]]`: +```c++ +// Will warn if return of foo() is ignored +[[nodiscard]] int foo(); +int main() { + int a {1}; + switch (a) { + // Indicates that falling through on case 1 is intentional + case 1: [[fallthrough]] + case 2: + // Indicates that b might be unused, such as on production builds + [[maybe_unused]] int b = foo(); + assert(b > 0); + break; + } +} +``` + ## C++17 Library Features ### std::variant diff --git a/README.md b/README.md index f6a80b1..d23ef50 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,7 @@ C++17 includes the following new language features: - [constexpr if](#constexpr-if) - [utf-8 character literals](#utf-8-character-literals) - [direct-list-initialization of enums](#direct-list-initialization-of-enums) +- [New standard attributes](#new-standard-attributes) C++17 includes the following new library features: - [std::variant](#stdvariant) @@ -454,6 +455,26 @@ byte d = byte{1}; // OK byte e = byte{256}; // ERROR ``` +### New standard attributes +C++17 introduces three new attributes: `[[fallthrough]]`, `[[nodiscard]]` and `[[maybe_unused]]`: +```c++ +// Will warn if return of foo() is ignored +[[nodiscard]] int foo(); + +int main() { + int a {1}; + switch (a) { + // Indicates that falling through on case 1 is intentional + case 1: [[fallthrough]] + case 2: + // Indicates that b might be unused, such as on production builds + [[maybe_unused]] int b = foo(); + assert(b > 0); + break; + } +} +``` + ## C++17 Library Features ### std::variant