C++属性attribute

C++属性attribute
目录〇基本信息一常用的C属性1 [[nodiscard]]2[[maybe_unused]]3[[deprecated]]4[[likely]] / [[unlikely]]二更多C属性1[[fallthrough]]2[[noreturn]]3[[carries_dependency]]三GCC扩展属性1aligned2packed3constructor / destructor4unused〇基本信息C 的属性Attributes是自 C11 引入的一种语言特性用于向编译器提供额外信息从而优化代码性能、提升可读性或抑制警告。属性不会改变程序的语义但可以影响编译器的行为例如优化、警告或代码生成。一常用的C属性1 [[nodiscard]]提示返回值不应被忽略[[nodiscard]] int CalculateResult() { return 42; }如果调用了CalculateResult但是没有接收返回值那么会触发编译告警。2[[maybe_unused]]抑制未使用变量的告警int main() { [[maybe_unused]] int unusedVariable 0; return 0; }对于写了一半的函数想先编译一下这个就很实用不会应该产生告警而编译失败。3[[deprecated]]标记函数为过时的[[deprecated(Use NewFunction instead)]] void OldFunction() {}4[[likely]] / [[unlikely]]提示编译器优化分支预测二更多C属性1[[fallthrough]]明确表示 switch 语句中的 case 是有意贯穿的。2[[noreturn]]指示函数不会返回。准确的讲是可以不返回但是也可以返回例如监测一个全局变量的值的代码以前是这么写的int x 0; int func() { while (true) { if (x 0)return x; } return 0; }但是最后的return 0其实是没有意义的不写也不行会报错。所以现在可以这样写[[noreturn]] int func() { while (true) { if (x 0)return x; } }3[[carries_dependency]]用于并行计算中表明变量依赖于其他变量。三GCC扩展属性GCC 提供了__attribute__系列的属性。1aligned指定对齐方式struct __attribute__((aligned(4))) AlignedStruct { int a; char b; short c; };2packed指定1字节对齐struct __attribute__((packed)) PackedStruct { int a; char b; short c; };3constructor / destructor指定函数在程序启动或结束时自动执行4unused标记未使用的变量或函数