如何知道是否移动一个物体

How to know if an object was moved

本文关键字:一个 何知道 是否 移动      更新时间:2023-10-16

这可能是一个愚蠢的问题,但我觉得我缺少一些设计模式。

在销毁班级期间,我想开展不同的操作。我考虑过实施一个简单的布尔值,该布尔被勾选时会被勾选。

这样:

class A {
    A(A && a) {
        a.was_moved = true;
    }
~A() {
    do some stuff
    if (!was_moved) {
        clean some more stuff
    }
bool was_moved = false;
};

这样做有"更好"的方法?我可以询问一些CPP功能是移动课还是一些已知的设计模式。

没有允许的功能。但是通常您不需要知道。

通常,当您定义移动构造函数时,您希望它将基础数据从一个对象"移动"到另一个对象。在您的上下文中,似乎您希望源对象之后为"空",以便只有一个所有者(毕竟是"移动",而不是"复制"(。因此

例如,假设您的类与文件描述符关联。然后,您可以将fd等于-1的默认值等于-1,并在其中区分destructor:

#include <utility>
class A
{
    public:
        A(int fd) : fd { fd }
        {
        }
        A(A&& other) : fd { std::exchange(other.fd, -1) }
        {
        }
        ~A()
        {
            if (fd != -1)
            {
                close(fd);
            }
        }
    private:
        int fd = -1;
};

当然,您可以通过附加标志将对象标记为空。确实,人们在某些特殊情况下这样做。即使在标准库中。您可能想阅读此。注意unique_lock类上的__owns_标志。

没有任何知道它的标准方式。但这很重要要定义移动构造函数和移动分配,以便您可以清理移动之前的Exisitng对象的资源:

class MoveDemo
{
    size_t size;
    char *buf;
    public:
    explicit MoveDemo(int sz=1024):size(sz), buf(new char[size]) {}
    ~MoveDemo { delete [] buf; }
    MoveDemo(MoveDemo&& other);
    MoveDemo& operator=(MoveDemo&& other);
};
MoveDemo::MoveDemo(MoveDemo&& other):size(0), buf(nullptr)
{
    size = other.size;
    buf = other.buf;
    //reset other
    other.size = 0;
    other.buf = nullptr;
}
MoveDemo& MoveDemo::operator=(MoveDemo&& other)
{
    if (this != &other)
    {
        // release current objects resources
        delete [] buf;
        size = 0;
        // move
        size = other.size;
        buf = other.buf;
        //reset other
        other.size = 0;
        other.buf = nullptr;
    }
    return *this;
}
相关文章: