使用const_cast实现move构造函数

Use const_cast to implement the move constructor

本文关键字:move 构造函数 实现 cast const 使用      更新时间:2023-10-16

我已经阅读了关于move构造函数的这一页。在那篇文章中,我们使用模板proxy来修改从函数返回的临时变量。

这是实现。

namespace detail {
    template <class T>
    struct proxy
    {
        T *resource_;
    };
} // detail
template <class T>
class MovableResource
{
private:
    T * resource_;
public:
    explicit MovableResource (T * r = 0) : resource_(r) { }
    ~MovableResource() throw() { delete resource_; }   // Assuming std:::auto_ptr like behavior.
    MovableResource (MovableResource &m) throw () // The "Move constructor" (note non-const parameter)
    : resource_ (m.resource_)
    {
        m.resource_ = 0; // Note that resource in the parameter is moved into *this.
    }
    MovableResource (detail::proxy<T> p) throw () // The proxy move constructor
    : resource_(p.resource_)
    {
        // Just copying resource pointer is sufficient. No need to NULL it like in the move constructor.
    }
    MovableResource & operator = (MovableResource &m) throw () // Move-assignment operator (note non-const parameter)
    {
        // copy and swap idiom. Must release the original resource in the destructor.
        MovableResource temp (m); // Resources will be moved here.
        temp.swap (*this);
        return *this;
    }
    MovableResource & operator = (detail::proxy<T> p) throw ()
    {
        // copy and swap idiom. Must release the original resource in the destructor.
        MovableResource temp (p);
        temp.swap(*this);
        return *this;
    }
    void swap (MovableResource &m) throw ()
    {
        std::swap (this->resource_, m.resource_);
    }
    operator detail::proxy<T> () throw () // A helper conversion function. Note that it is non-const
    {
        detail::proxy<T> p;
        p.resource_ = this->resource_;
        this->resource_ = 0;     // Resource moved to the temporary proxy object.
        return p;
    }
};

如果只是添加一个构造函数,接受const引用,并使用const_cast来改变变量,以实现像这样的移动语义。

MovableResource(const MovableResource& m)
{
    MovableResource& afterM = const_cast<MovableResource&>(m);
    afterM.swap(*this);
}

这会引入未定义行为吗?

在复制构造函数接口下实现move语义只是自找麻烦。通过使用const_cast,您可以有效地欺骗接口的客户端,使其相信您的构造函数在最终修改其值时不会修改m。考虑下面的代码:

const MovableResource first(/* Some resource 'A' */);
MovableResource second(first);
// 'first', supposedly 'const' now has potentially a different value!

MovableResource (MovableResource &m) throw()//"Move构造函数"(注意非const参数)

不是move构造函数,而是copy构造函数。正确的move构造函数接受右值引用作为输入:

MovableResource (MovableResource &&m) throw ()

MovableResource,operator = (MovableResource &m) throw()//移动赋值操作符(注意非const形参)

同样,

也是一个复制赋值操作符。正确的move赋值操作符接受右值引用作为输入:

MovableResource & operator = (MovableResource &&m) throw ()