std :: optional实现为union vs char []/aligned_storage [英] std::optional implemented as union vs char[]/aligned_storage

查看:126
本文介绍了std :: optional实现为union vs char []/aligned_storage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读GCC的std::optional实现时,我注意到了一些有趣的东西.我知道boost::optional的实现方式如下:

While reading through GCC's implementation of std::optional I noticed something interesting. I know boost::optional is implemented as follows:

template <typename T>
class optional {
    // ...
private:
    bool has_value_;
    aligned_storage<T, /* ... */> storage_;
}

但是随后 libstdc ++ libc ++ (以及 Abseil )都实现了它们的optional类型,如下所示:

But then both libstdc++ and libc++ (and Abseil) implement their optional types like this:

template <typename T>
class optional {
    // ...
private:
    struct empty_byte {};
    union {
        empty_byte empty_;
        T value_;
    };
    bool has_value_;
}

在我看来,它们在功能上是相同的,但是使用它们相对于其他有什么好处吗? (除了后者中明显缺少新的位置,这确实很好.)

They look to me as they are functionally identical, but are there any advantages of using one over the other? (Except for the obvious lack of placement new in the latter which is really nice.)

推荐答案

在我看来,它们在功能上是相同的,但是使用它们相对于其他有什么好处吗? (除了后者中明显的新缺席,这确实不错.)

They look to me as they are functionally identical, but are there any advantages of using one over the other? (Except for the obvious lack placement new in the latter which is really nice.)

这不仅是真正的好",而且对于真正重要的功能至关重要,即:

It's not just "really nice" - it's critical for a really important bit of functionality, namely:

constexpr std::optional<int> o(42);

在常量表达式中, 不能做的几件事,包括newreinterpret_cast.如果使用aligned_storage实现optional,则需要使用new创建对象,并使用reinterpret_cast将其取回,这将阻止optional友好constexpr.

There are several things you cannot do in a constant expression, and those include new and reinterpret_cast. If you implemented optional with aligned_storage, you would need to use the new to create the object and reinterpret_cast to get it back out, which would prevent optional from being constexpr friendly.

使用union实现,您就不会遇到此问题,因此可以在constexpr编程中使用optional(甚至在 Nicol 在谈论,已经需要 optional 可用作constexpr).

With the union implementation, you don't have this problem, so you can use optional in constexpr programming (even before the fix for trivial copyability that Nicol is talking about, optional was already required to be usable as constexpr).

这篇关于std :: optional实现为union vs char []/aligned_storage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆