在 C++17 中,新的 std::optional
如果 T
在 [optional.object.dtor] 中很容易被破坏:
~optional();
1 Effects: Ifis_trivially_destructible_v<T> != true
and*this
contains a value, callsval->T::~T()
.
2 Remarks: Ifis_trivially_destructible_v<T> == true
then this destructor shall be a trivial destructor.
所以这个潜在的实现片段将不符合标准:
template <class T>
struct wrong_optional {
union { T value; };
bool on;
~wrong_optional() { if (on) { value.~T(); } }
};
我的问题是:这个授权有什么好处?据推测,对于一般可破坏的类型,编译器可以计算出 value.~T()
是一个无操作并且不为 wrong_optional<T>::~wrong_optional()
发出任何代码.
最佳答案
std::optional
已经有 constexpr
constructors .当它的析构函数很简单时,它是 literal type .只能在常量表达式中创建和操作文字类型的对象。
关于c++ - 琐碎破坏的意义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41897418/