STL <memory>
header (MSVC 实现)包含一个名为:
template <class _Ty> class _Ref_count_obj2 : public _Ref_count_base
这个类有一个成员:
union {
_Wrap<_Ty> _Storage;
};
其中 _Wrap 定义为:
template <class _Ty>
struct _Wrap {
_Ty _Value; // workaround for "T^ is not allowed in a union"
};
根据我的理解,此代码旨在通过 new
构造后保存一个 _Ty 类型的对象。运算符(operator)。但是我不明白为什么要这样做;好像在用 struct
而不是 struct
在 union
里面也可以。
谁能解释一下这背后的原因?另外,谁能解释一下 _Wrap 定义中的注释?
最佳答案
首先,嵌入 _Storage
union
中的成员将防止默认销毁该对象(很可能是非平凡类型);这似乎是必不可少的,因为所涉及的类是一个引用计数器。 (默认情况下, union 有一个已删除的析构函数;参见,例如:Is a Union Member's Destructor Called。)
其次,使用匿名 union
'移动' _Storage
标识符进入封闭范围,从而消除对 X.
的任何需要-style 符号(如果 union 被命名为 X
)。来自 cppreference :
Members of an anonymous union are injected in the enclosing scope (and must not conflict with other names declared there).
最后,需要将 union 的成员包装到模板结构中,这样类才能使用引用类型,这在 union 中是不允许的。要检查最后一部分,请尝试使用以下代码并激活注释掉的行:
template <class _Ty> struct _Wrap { _Ty _Value; // workaround for "T^ is not allowed in a union" }; template<class T> class bob { public: bob(T t) : uncle{t}//, aunty(t) { } private: union { _Wrap<T> uncle; }; // union { // T aunty; // }; }; int main() { int i = 42; bob<int&> b{ i }; // Note: Template uses a REFERENCE type return 0; }
关于c++ - 为什么要将结构包装在匿名 union 中? (STL msvc 实现),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62580895/