如何知道是否移动一个物体
How to know if an object was moved
这可能是一个愚蠢的问题,但我觉得我缺少一些设计模式。
在销毁班级期间,我想开展不同的操作。我考虑过实施一个简单的布尔值,该布尔被勾选时会被勾选。
这样:
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;
}
相关文章:
- 我正在尝试使用 c++ 创建一个货币转换程序,我不知道如何继续
- 为什么需要知道一个类是平凡的还是有平凡的构造函数
- 我正在尝试制作一个自平衡机器人,但编译时存在错误。我不知道如何解决它
- 如何知道地图中的最后一个元素是否被删除?
- 如何在不知道对应关系的情况下在字符串中搜索字符并将其分配给另一个字符?
- 创建一个带有 lambda 的 std::函数,而不知道函数的参数
- 在矢量中使用擦除时双重释放或损坏(快速顶部).如何擦除一个矢量的几个项目知道它们的索引?
- 我已经做了一个程序来使用队列链C++表显示学生姓名和身高,现在我想以我不知道如何显示的顺序显示它
- 我想知道我是否可以将一个类分配给特定的成员数据并创建该类的实例
- 我创建了一个库,想知道设计是否效率低下
- 创建一个始终返回零但优化器不知道的函数
- 我对C++程序有一个未定义的参考,不知道如何处理它
- 我正在编写一个拆分为 3 的合并排序,我不知道为什么它不起作用
- 我想知道我将如何实现 + 运算符重载.我已经从我上一个问题中计算出 += 运算符重载
- 有没有机会触发一个不知道拥有队列的kevent?还有其他选择吗?
- 获取一个不知道长度 C++ 的子字符串
- 我需要检查一个接一个地知道哪个单选按钮在Qt组检查
- 如何实例化一个只知道其名称的对象
- 物品-库存-关系,其中一个应该知道另一个
- 如何使一个qwidget知道另一个qwidget在它上面