首页 > 解决方案 > 清除具有已删除赋值运算符的成员的类实例

问题描述

我想使用赋值运算符清除/重新实例化一个类的实例,但是该类中的某些成员的赋值运算符被删除了。因此,当我尝试将其分配给新实例时,它会保留其旧值。

这是一个例子:

#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;
}

在不编写清除所有成员的方法的情况下,是否有一些简单的解决方法?为什么会这样?

标签: c++

解决方案


为什么会这样?

您当前的实现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;
}

推荐阅读