注:本节提到的属性,均指attribute

9.12.7 Maybe unused attribute

1
attribute-token`maybe_unused`指示一个名称或实体可能是有意未被使用的。它在每个attribute-list中最多出现一次,且不得带有attribute-argument-clause(不得带有属性实参,即不可写为`[[maybe_unused(xxx)]]`)。
2
此属性可以应用于以下实体的声明: 类、类型别名([typedef-name]())、变量(包括结构化绑定声明)、非静态数据成员、函数、枚举或枚举成员。
Paw5zx个人理解:点击查看更多
1
2
3
4
5
6
7
8
9
10
11
[[maybe_unused]] class C {};          // 类
[[maybe_unused]] typedef int I; // typedef 类型别名
[[maybe_unused]] int x = 42; // 变量
[[maybe_unused]] int a, b; // 多个变量
struct S
{
[[maybe_unused]] int member; // 非静态数据成员
};
[[maybe_unused]] void func(); // 函数
enum [[maybe_unused]] E { A, [[maybe_unused]] B }; // 枚举与枚举成员

3
未使用maybe_unused属性声明的名称或实体,可以在其后的重新声明中带上该属性;反之亦然(最初带有该属性的声明,在后续的重新声明中可以不再重复书写该属性)

一个实体,自首次带有该属性的声明起,该实体即被视为已标记。

4
推荐实践: 对于带有maybe_unused标记的实体,实现不应因该实体或其结构化绑定(若有)被使用或未被使用而发出警告。 对于未带有maybe_unused标记的结构化绑定声明,实现不应发出此类警告,除非其所有的结构化绑定均未被使用。
5

【示例:

1
2
3
4
5
6
[[maybe_unused]] void f([[maybe_unused]] bool thing1,
[[maybe_unused]] bool thing2)
{
[[maybe_unused]] bool b = thing1 && thing2;
assert(b);
}

无论是否定义了NDEBUG,实现都不应警告b未被使用。 ——示例结束】

9.12.10 No unique address attribute

1
attribute-token`no_unique_address`指示一个非静态数据成员是潜在可重叠的子对象(见[[intro.object]]())。它在每个attribute-list中最多出现一次,且不得带有attribute-argument-clause。属性可以附着于除位域之外的非静态数据成员。
2
【注:非静态数据成员可以与另一个非静态数据成员或一个基类共享地址,并且通常在对象末尾插入的那些填充字节可以被重新利用,作为其他成员的存储空间。——注释结束】【示例:
1
2
3
4
5
6
7
8
9
10
11
template<typename Key, typename Value,
typename Hash, typename Pred, typename Allocator>
class hash_map {
[[no_unique_address]] Hash hasher;
[[no_unique_address]] Pred pred;
[[no_unique_address]] Allocator alloc;
Bucket *buckets;
// ...
public:
// ...
};

上例中,若hasherpredalloc各自的类型都是空类,则它们可以与buckets具有相同的地址。