Skip to content

Latest commit

 

History

History
117 lines (88 loc) · 2.96 KB

File metadata and controls

117 lines (88 loc) · 2.96 KB

Attributes


Attributes

Attributes provide the unified standard syntax for implementation-defined language extensions, such as the GNU and IBM language extensions __attribute__((...)), Microsoft extension declspec(), etc.

Standard attributes

  • [[noreturn]] - function does never return, like std::terminate. If it does, we have UB
  • [[deprecated]] (C++14) - function is deprecated
  • [[deprecated("reason")]] (C++14) - as above, but compiler will emit the reason
  • [[fallthrough]] (C++17) - in switch statement, indicated that fall through is intentional
  • [[nodiscard]] (C++17) - you cannot ignore value returned from function
  • [[maybe_unused]] (C++17) - suppress compiler warning on unused class, typedef, variable, function, etc.

[[noreturn]] attribute

[[noreturn]] void f() {
    throw "error";
    // OK
}

[[noreturn]] void q(int i) {
    if (i > 0) {
        throw "positive";
    }
    // the behavior is undefined if called with argument <=0
}

[[fallthrough]] attribute

void f(int n){
    void g(), h(), i();
    switch(n) {
    case 1:
    case 2:
        g();
        [[fallthrough]];
    case 3: // no warning on fallthrough
        h();
    case 4: // compiler may warn on fallthrough
        i();
        [[fallthrough]]; // illformed, not before a case label
    }
}

[[nodiscard]] attribute

struct [[nodiscard]] error_info {};
error_info process(Data*);

// ...

void passMessage() {
    auto data = getData();
    process(data);  // compiler warning, discarding error_info
}

[[maybe_unused]] attributes

[[maybe_unused]] void f([[maybe_unused]] bool thing1,
                        [[maybe_unused]] bool thing2)
{
  [[maybe_unused]] bool b = thing1 && thing2;
  assert (b); // in release mode, assert is compiled out, and b is unused
              // no warning because it is declared [[maybe_unused]]
} // parameters thing1 and thing2 are not used, no warning

[[deprecated]] attribute

Attributes for namespaces and enumerators are available from C++17.

[[deprecated("Please use f2 instead")]] int f1();

enum E {
    foobar = 0,
    boobat [[deprecated]] = foobar
};
E e = foobat; // Emits warning

namespace [[deprecated]] old_stuff {
    void legacy();
}
old_stuff::legacy(); //Emits warning

Exercise

Add a new method double getPi() in Circle class, which returns a PI number. Mark it as deprecated.