c++ - 清除具有已删除赋值运算符的成员的类实例
问题描述
我想使用赋值运算符清除/重新实例化一个类的实例,但是该类中的某些成员的赋值运算符被删除了。因此,当我尝试将其分配给新实例时,它会保留其旧值。
这是一个例子:
#include <cstdio>
class C
{
C operator= (const C&) = delete;
};
class B
{
public:
int x = 0;
C c;
B& operator=(const B& other)
{
return B();
}
};
int main()
{
B b;
b.x = 5;
b = B();
printf("%i\n", b.x); // prints 5, should print 0
return 0;
}
在不编写清除所有成员的方法的情况下,是否有一些简单的解决方法?为什么会这样?
解决方案
为什么会这样?
您当前的实现operator=()
是 fubar。
B& operator=(B const &other)
{
x = other.x;
return *this;
}
但是,您还应该在做任何事情之前测试自我分配,因为复制成员可能非常昂贵:
B& operator=(B const &other)
{
if(this != &other)
x = other.x;
return *this;
}
推荐阅读
- swift - NSError.setUserInfoValueProvider 无限循环
- php - 如何在 macOS 上配置 PHP 以对 SQL Server 使用 Windows 身份验证?
- python - Django DRF 关注关系
- c# - 使用用户上下文 GUI 在 C# WPF 应用程序中运行管理后台工作
- c# - 在 C# / Unity 中平衡化学方程式
- javascript - 为什么javascript中这个yield生成器的迭代次数有误?
- c# - 将随机值从列表分配到列表C#
- php - GraphQL - 如何保存嵌套数据
- python - 为什么 sklearn 的 PCA 不返回可重现的结果?
- python - 如何在张量流中一次只加载一批图像?