c – 通过其成员的地址激活嵌套联盟是否合法?

前端之家收集整理的这篇文章主要介绍了c – 通过其成员的地址激活嵌套联盟是否合法?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
以下代码是否合法(在c 11/14中)?
  1. bool foo() {
  2. union bar { int i; bool b; };
  3. union baz { char c; bar b; };
  4. auto b = baz{'x'};
  5. auto barptr = &b.b;
  6. auto boolptr = &barptr->b;
  7. new (boolptr) bool{true};
  8. return b.b.b;
  9. }

这个例子很愚蠢,但我正在使用一个可变参数变体实现,它使用嵌套联合而不是变量成员的char []块,并且允许这将使我当前在复制构造函数中的尝试变得更清晰.

将其细分为两个子问题:

>即使b.b处于非活动状态,是否通过访问barptr legal的成员来分配boolptr?
> boolptr的就地构造是否会激活b.b和b.b.b?

将赞赏对该标准的参考.

解决方法

正如关于工会和类型惩罚的许多问题一样,目前还不清楚你的程序是否已经定义了行为,尽管我强烈期望它在任何理智的实现中都能按预期运行.我可以肯定地说,this program
  1. #include <memory>
  2. #include <new>
  3.  
  4. template <typename T>
  5. inline void destruct(T& t) { t.~T(); }
  6.  
  7. template <typename T,typename...Args>
  8. inline void construct(T& t,Args&&...args) {
  9. ::new((void*)std::addressof(t)) T(std::forward<Args>(args)...);
  10. }
  11.  
  12. template <typename T>
  13. inline void default_construct(T& t) {
  14. ::new((void*)std::addressof(t)) T;
  15. }
  16.  
  17. bool foo() {
  18. union bar { int i; bool b; };
  19. union baz { char c; bar b; };
  20. auto b = baz{'x'};
  21. destruct(b.c);
  22. default_construct(b.b);
  23. construct(b.b.b,true);
  24. return b.b.b;
  25. }

符合标准,具有您想要的效果,compiles to exactly the same assembly as the original program in modern compilers.Original

  1. foo():
  2. movl $1,%eax
  3. ret

Guaranteed-compliant

  1. foo():
  2. movl $1,%eax
  3. ret

猜你在找的C&C++相关文章