簡體   English   中英

清除具有刪除了賦值運算符的成員的類實例

[英]Clearing a class instance with a member that has a deleted assignment operator

我想使用賦值運算符清除/重新實例化類的實例,但是該類中的某些成員刪除了其賦值運算符。 因此,當我嘗試將其分配給新實例時,它將保留其舊值。

這里是一個例子:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM