c++ - 为什么要将结构包装在匿名 union 中? (STL msvc 实现)

标签 c++ templates struct unions c++-standard-library

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而不是 structunion 里面也可以。

谁能解释一下这背后的原因?另外,谁能解释一下 _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/

相关文章:

c++ - 如何关闭 std::fixed 并返回默认的 C++ 设置

templates - 测试别名是否是 D 2.0 中的模板

c - 传递一个包含 NULL 的结构指针突然包含一个结构而不是 NULL

c++ - 为什么C++中有这么多字符串类型?

c++ - 读取数据文件并将每一列分配给单独的数组

c++ - 在C++中四舍五入

c++如何减少相同模板特化的数量?

c++ - 如何修复涉及概念和 friend 的 C++20 编译错误?

c - 命令行参数和结构体参数

c - C 中的数据隐藏,多态行为?