目录
〇,基本信息
一,常用的C++属性
1, [[nodiscard]]
2,[[maybe_unused]]
3,[[deprecated]]
4,[[likely]] / [[unlikely]]
二,更多C++属性
1,[[fallthrough]]
2,[[noreturn]]
3,[[carries_dependency]]
三,GCC扩展属性
1,aligned
2,packed
3,constructor / destructor
4,unused
〇,基本信息
C++ 的属性(Attributes)是自 C++11 引入的一种语言特性,用于向编译器提供额外信息,从而优化代码性能、提升可读性或抑制警告。属性不会改变程序的语义,但可以影响编译器的行为,例如优化、警告或代码生成。
一,常用的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__系列的属性。
1,aligned
指定对齐方式
struct __attribute__((aligned(4))) AlignedStruct { int a; char b; short c; };2,packed
指定1字节对齐
struct __attribute__((packed)) PackedStruct { int a; char b; short c; };3,constructor / destructor
指定函数在程序启动或结束时自动执行
4,unused
标记未使用的变量或函数