【发布时间】:2020-10-28 06:30:33
【问题描述】:
我已经多次阅读新的 c++20 功能 no_unique_address,我希望有人能用一个比下面这个来自 c++ 参考的例子更好的例子来解释和说明。
说明适用于在声明中声明的名称 不是位域的非静态数据成员。
表明这个数据成员不需要有一个不同于 其类的所有其他非静态数据成员。这意味着,如果 成员具有空类型(例如无状态分配器),编译器可能 优化它以不占用空间,就像它是一个空基地一样。如果 该成员不为空,其中的任何尾部填充也可以重用于 存储其他数据成员。
#include <iostream>
struct Empty {}; // empty class
struct X {
int i;
Empty e;
};
struct Y {
int i;
[[no_unique_address]] Empty e;
};
struct Z {
char c;
[[no_unique_address]] Empty e1, e2;
};
struct W {
char c[2];
[[no_unique_address]] Empty e1, e2;
};
int main()
{
// e1 and e2 cannot share the same address because they have the
// same type, even though they are marked with [[no_unique_address]].
// However, either may share address with c.
static_assert(sizeof(Z) >= 2);
// e1 and e2 cannot have the same address, but one of them can share with
// c[0] and the other with c[1]
std::cout << "sizeof(W) == 2 is " << (sizeof(W) == 2) << '\n';
}
- 谁能向我解释一下这个功能背后的目的是什么?我应该什么时候使用它?
- e1 和 e2 不能有相同的地址,但其中一个可以与 c[0] 共享,另一个与 c[1] 共享 有人可以解释一下吗?为什么我们会有这样的关系?
【问题讨论】:
-
这是一个很乐意使用它的人 stackoverflow.com/questions/57460260/… 然后是 EBO 的古老用途 stackoverflow.com/questions/4325144/… - 除了我们可以使用组合而不是滥用继承
-
godbolt 上的 gcc (trunk) 和 clang (trunk) 都不能生成
sizeof(W) == 2(链接示例中的struct A),但是如果[[no_unique_address]]的声明在其他声明之前,它们都会这样做。 Example
标签: c++ attributes c++20