gpt4 book ai didi

c++ - std::optional 实现为 union vs char[]/aligned_storage

转载 作者:可可西里 更新时间:2023-11-01 16:27:16 25 4
gpt4 key购买 nike

在阅读 GCC 对 std::optional 的实现时,我注意到了一些有趣的事情。我知道 boost::optional 实现如下:

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

但是 libstdc++libc++(以及 Abseil)都像这样实现它们的可选类型:

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

在我看来,它们在功能上是相同的,但是使用一个比另一个有什么优势吗? (除了后者明显缺少 new placement 之外,这非常好。)

最佳答案

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.)

这不仅仅是“非常好”——它对于一个非常重要的功能来说至关重要,即:

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

不能在常量表达式中做几件事,包括newreinterpret_cast。如果您使用 aligned_storage 实现了 optional,则需要使用 new 来创建对象并使用 reinterpret_cast 来获取它退出,这将阻止 optional 成为 constexpr 友好的。

使用 union 实现,你没有这个问题,所以你可以在 constexpr 编程中使用 optional (甚至在 fix for trivial copyability 之前Nicol 正在谈论,optional 已经被要求用作 constexpr)。

关于c++ - std::optional 实现为 union vs char[]/aligned_storage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52338255/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com