被移动对象是否需要被破坏? [英] Are moved-from objects required to be destructed?

查看:85
本文介绍了被移动对象是否需要被破坏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我从 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 初始化使用三值枚举来区分初始化,非初始化和移出。

是的,仍然有必要销毁

b 。从对象移动是一个有效的,构造的对象。在某些情况下,它甚至可能拥有仍然需要处理的资源。在诸如你显示的通用代码中, 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屋!

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