移动分配和引用成员 [英] Move-assignment and reference member

查看:113
本文介绍了移动分配和引用成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具有引用成员变量的类的复制分配是一个no-no,因为您不能重新分配引用。但是移动任务呢?我尝试简单地 move 它,但是,当然,当我只是想移动引用本身时,破坏源对象:

  class C 
{
public:
C(X& x):x_(x){}
C(C& ;& other):x_(std :: move(other.x_)){}
C& operator =(C&& other)
{
x_ = std :: move(other.x_);
}
private:
X& X_;
};

X y;
C c1(y);

X z;
C c2(z);

c2 = c1; //破坏y以及z

我应该只是不执行移动任务和坚持移动只有建设?这使得交换(C& amp;)很难实现。

解决方案

p>(作为OP建议的评论的回答)



一般来说,如果想用C ++中的引用做一些不平凡的东西, reference_wrapper< T> ,这本质上是 T& 的花式价值语义替代,完成它 - 它已经提供(重)分配和其他操作。我相信这将使移动构造函数和赋值接近平凡,如果不是微不足道(注意琐碎 is_trivially _ * semantics)。



参考包装器作为TR1的一部分添加到C ++ 03中, >

文档: http://en.cppreference.com/ w / cpp / utility / functional / reference_wrapper


Copy-assignment for a class with a reference member variable is a no-no because you can't reassign the reference. But what about move-assignment? I tried simply moveing it but, of course, that destroys the source object when I just want to move the reference itself:

class C
{
public:
    C(X& x) : x_(x) {}
    C(C&& other) : x_(std::move(other.x_)) {}
    C& operator=(C&& other)
    {
        x_ = std::move(other.x_);
    }
private:
    X& x_;
};

X y;
C c1(y);

X z;
C c2(z);

c2 = c1; // destroys y as well as z

Should I just not be implementing move-assignment and sticking with move-construction only? That makes swap(C&, C&) hard to implement.

解决方案

(Posted as an answer from comment as suggested by the OP)

In general if one wants to do non-trivial stuff with references in C++, one would be using reference_wrapper<T>, which is essentially a fancy value-semantic stand-in for a T&, then one would be done with it - it already provides (re)assignment and other operations. I'm sure that would make move constructor and assignment near-trivial, if not trivial (note not trivial as in per the is_trivially_* semantics).

"Reference wrapper" is added to C++03 as part of TR1, and is part of C++11.

Documentation: http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper

这篇关于移动分配和引用成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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