被移动对象是否需要被破坏? [英] Are moved-from objects required to be destructed?
问题描述
如果我从 b
中移动构建 a
,仍然需要 破坏 b
,或者我可以不这样做吗?
可选< T>
模板。摘录:
〜可选()
{
if(初始化)
{
reinterpret_cast< T *>(data) - >〜T();
}
}
可选(可选& o):已初始化(o.initialized)
{
if(已初始化)
{
new(data)T(std :: move(* o)); // move from o.data
o.initialized = false; // o.data不会被破坏了!
}
}
当然,我可以替换bool 初始化
使用三值枚举来区分初始化,非初始化和移出。
是的,仍然有必要销毁。
T
甚至可能没有移动构造函数。在这种情况下,您可以调用复制构造函数。所以你绝对不能假设〜T()是一个无操作,可以省略。 If I move-construct a
from b
, is it still necessary to destruct b
, or can I get away without doing so?
This question crossed my mind during the implementation of an optional<T>
template. Excerpt:
~optional()
{
if (initialized)
{
reinterpret_cast<T*>(data)->~T();
}
}
optional(optional&& o) : initialized(o.initialized)
{
if (initialized)
{
new(data) T(std::move(*o)); // move from o.data
o.initialized = false; // o.data won't be destructed anymore!
}
}
Of course, I could just replace the bool initialized
with a three-valued enumeration that distinguishes between initialized, non-initialized and moved-from. I just want to know if this is strictly necessary.
Yes, it is still necessary to destruct b
. A moved from object is a valid, constructed object. In some cases, it may even hold resources that still need to be disposed of. In generic code such as you show, T
may not even have a move constructor. You may invoke a copy constructor instead in this case. So you can definitely not assume that ~T() is a no-op and can be elided.
这篇关于被移动对象是否需要被破坏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!