C++ attribute 简介
C++ 的 attribute 是一种标准的语法结构来对语言进行扩展,用来统一各种编译器的自定义扩展,例如 gcc 的 __attribute__((...)) ,或者微软的 __declspec() 。
C++ 语言本身定义了一些标准的 attribute ,例如 [[ noreturn ]] 、 [[ nodiscard ]] 等,也支持编译器特定的 attribute ,例如 [[ gnu::unused ]] 等,
C++20 对 [[ nodiscard ]] 的改进
在 C++17 中引入了 [[ nodiscard ]] 属性,主要是用来标记一个对象或者一个函数,通知编译器这个对象或者这个函数返回的对象不应该被丢弃,如果被丢弃了,编译器应该发出警告。
C++20 在 C++17 的基础上,对 [[ nodiscard ]] 属性进行了改进:
- 支持 [[ nodiscard ]] 属性增加参数,用于说明理由
- 对于构造函数也标记 [[ nodiscard ]] 属性
下面通过一些例子来说明 [[ nodiscard ]] 属性:
#include using std::cout, std::endl;// <1> 类本身是 nodiscard ,函数返回这个类的对象时不可丢弃struct [[ nodiscard("for example, maybe memory leak") ]] SA{ int m_a;};struct SC{ SC() : m_b( 7 ) {} // <2> 普通构造函数 [[ nodiscard ]] SC( int fd, int b ) : m_b ( b ) {} // <3> 特定的构造函数,构建的对象不可丢弃 int m_b;};// <21> 函数返回的对象不可丢弃struct SA func_1(){ return SA { 5 };}// <22> 返回的是对象的引用,而不是对象,不同的类型,因此不算不可丢弃struct SA & func_2(){ static SA a1 { 5 }; return a1;}// <23> 函数本身有nodiscard标记,不管返回什么对象都不可丢弃[[ nodiscard ]] struct SC func_3(){ return SC();}// <24> 普通函数,SC类也只是某些构造函数不可丢弃,不是整个类本身不可丢弃,