首页 > 编程语言 >c++17 注解标签 attributes & c++ 枚举值

c++17 注解标签 attributes & c++ 枚举值

时间:2022-10-29 11:55:50浏览次数:50  
标签:std 17 int 枚举 c++ 编译器 attributes white

c++ 标注

c++17 后逐渐完善

注解标签语法:[[attribute]] types/functions/enums/etc 

  1. 告诉编译器没有返回值 [[noreturn]]
    常用于系统函数设计,如 std::abort() std::exit();
    [[noreturn]] void terminate();
  2. [[deprecated]] 标注函数或类型已被弃用
    [[deprecated]] void funcX();
    
    [[deprecated("use funY instead")]] void funcX();
  3. [[fallthrough]] 当switch-case 分支完毕后没有break时,取消警告
    switch(type) {
        case 1:
            fun1();  // 这里没有break,所以编译器会给出警告
        [[fallthrough]]; // g++中无需分号,vs中必须有分号
        case 2:
            fun2();  // 因为有 [[fallthrough]] 所以编译器不会警告
    }
  4. [[nodiscard]] 修饰函数,返回值必须被使用
    [[nodiscard]] int fun() { return 0; }
    
    int main() {
      fun();   // 此处没有变量接收返回值,编译器给出警告
      return 0;
    }

    c++20 中对于 operator new()  std::allocate() 等库函数均使用了 [[nodiscard]] 进行标记

  5. [[maybe_unused]] 标注函数或变量不再被使用
    int WINAPI wWinMain(HINSTANCE hInstance,
                       [[maybe_unused]] HINSTANCE hPrevInstance,
                       [[maybe_unused]] LPWSTR lpCmdLine,
                       int nCmdShow)
    {
      // ...
    }

c++ 枚举

/***************** c++98/03 enumeration******************/
enum Color {
  black,
  white
};

bool white = true; // 编译不通过,与枚举值冲突

/******************** c++11 enumerator ********************/

enum class Color {
    black,
    white
};

bool white = true; // 编译通过,枚举值外部不可见,必须通过 Color::white 引用

 

标签:std,17,int,枚举,c++,编译器,attributes,white
From: https://www.cnblogs.com/zhh567/p/16838418.html

相关文章