简体   繁体   English

移动分配和引用成员

[英]Move-assignment and reference member

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 move ing it but, of course, that destroys the source object when I just want to move the reference itself: 我试过简单地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; // 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. 这使得swap(C&, C&)难以实现。

(Posted as an answer from comment as suggested by the OP) (根据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. 一般来说,如果一个人想要用C ++中的引用做一些非平凡的事情,那么就会使用reference_wrapper<T> ,这对于T&来说本质上是一种奇特的价值语义替代,然后就可以用它完成 - 它已经完成了提供(重新)分配和其他操作。 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). 我敢肯定,如果不是微不足道的话,那会使移动构造函数和赋值变得非常平凡(注意,根据is_trivially_*语义,这并不trivial )。

"Reference wrapper" is added to C++03 as part of TR1, and is part of C++11. “参考包装器”作为TR1的一部分添加到C ++ 03中,是C ++ 11的一部分。

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

A reference is, in some sense, a T *const with syntactic sugar on top to auto-derefence, auto-capture, and auto-lifetime extend temporaries. 在某种意义上,参考是具有语法糖的T *const ,其顶部是自动消除,自动捕获和自动生命延长时间。 (note that this is not quite true, but often is in practice and practicality) (请注意,这不是真的,但通常是在实践和实践中)

If you want a reseatable reference, C++ has those: they are called pointers. 如果你想要一个可重新引用的引用,C ++有:它们被称为指针。 You can use an accessor to replace dereferencing with a function call if you like. 如果您愿意,可以使用访问器将取消引用替换为函数调用。 The remaining feature (temporary lifetime extension) that is hard to emulate does not apply to struct members. 难以模拟的其余功能(临时生命周期扩展)不适用于struct成员。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM