通过成员地址激活嵌套工会合法吗
Is it legal to activate nested unions via the address of their members?
以下代码合法吗(在c++11/14中)?
bool foo() {
union bar { int i; bool b; };
union baz { char c; bar b; };
auto b = baz{'x'};
auto barptr = &b.b;
auto boolptr = &barptr->b;
new (boolptr) bool{true};
return b.b.b;
}
这个例子很傻,但我正在讨论一个可变的variant
实现,该实现使用嵌套的并集而不是用于可变成员的char []
块,允许这样做将使我当前在复制构造函数方面的尝试更加干净。
将其分解为两个子问题:
- 即使
b.b
处于非活动状态,通过访问barptr
的成员来分配boolptr
是否合法 boolptr
的原位构建是否激活b.b
和b.b.b
请参考本标准。
关于并集和类型双关的许多问题都不清楚您的程序是否定义了行为,尽管我强烈希望它在任何正常的实现中都能像预期的那样运行。我可以肯定地说,这个程序:
#include <memory>
#include <new>
template <typename T>
inline void destruct(T& t) { t.~T(); }
template <typename T, typename...Args>
inline void construct(T& t, Args&&...args) {
::new((void*)std::addressof(t)) T(std::forward<Args>(args)...);
}
template <typename T>
inline void default_construct(T& t) {
::new((void*)std::addressof(t)) T;
}
bool foo() {
union bar { int i; bool b; };
union baz { char c; bar b; };
auto b = baz{'x'};
destruct(b.c);
default_construct(b.b);
construct(b.b.b, true);
return b.b.b;
}
符合标准,具有您想要的效果,并且在现代编译器中编译为与原始程序完全相同的程序集。原件:
foo():
movl $1, %eax
ret
保证合规:
foo():
movl $1, %eax
ret
相关文章:
- 嵌套在类中时无法设置成员数据
- 如何在 C++ 的外部类构造函数中初始化嵌套类成员
- 迭代嵌套映射与范围为循环:没有名为"first"的成员
- 如何从另一个嵌套类中调用某个封闭类的嵌套类的函数指针成员的值?
- MSVC 2017 - 错误 - 如何将模板类 X 的模板成员函数声明为嵌套类 X::Y 的好友
- std::void_t 和嵌套的非类型成员
- C2436 '{ctor}':构造函数初始值设定项列表中的成员函数或嵌套类
- c++ 嵌套结构映射找不到成员
- 无法从多态嵌套类访问包含类的成员
- 其他类的成员函数对成员函数的嵌套引用
- 如何从嵌套在命名空间中的类调用成员函数?
- 返回自身内部的双重嵌套类的成员函数,该类继承自从自身继承的类
- 嵌套的类成员变量不可访问.链表设置.V、下一个和新的问题
- 当使用嵌套类功能时,使用非静态数据成员的使用无效,但是当函数未固定时可以
- 包含指针成员的嵌套结构
- 缩短成员函数作用域说明符(嵌套类)(C++)
- 为什么嵌套类的成员函数不需要完整类型?
- 使用泛型函数调用打印结构的所有嵌套成员变量
- 嵌套成员类型识别
- 初始化构造函数中嵌套成员的语法