我想知道下面的代碼是否安全,考慮到子物件被隱式轉換為型別Parent
然后從記憶體中移動。換句話說,當傳遞other
給Parent::operator=(Parent&&)
from時Child::operator(Child&&)
,是整個物件被父呼叫“移動”了,還是只是底層Parent
物件?
class Parent
{
public:
// Constructors
Parent& operator=(Parent&& other) noexcept
{
if (this == &other)
return *this;
str1_ = std::move(other.str1_);
str2_ = std::move(other.str2_);
return *this;
}
protected:
std::string str1_, str2_;
};
class Child : public Parent
{
public:
// Constructors
Child& operator=(Child&& other) noexcept
{
if (this == &other)
return *this;
// Are the following 2 lines memory safe?
Parent::operator=(std::move(other));
str3_ = std::move(other.str3_);
return *this;
}
private:
std::string str3_;
};
uj5u.com熱心網友回復:
你正在做的事情是安全的。您只是將對基類子物件的參考傳遞給基賦值運算子。std::move
不移動任何東西。它只是從左值中生成一個 xvalue,以便右值參考可以系結到它。這里的系結是針對子物件的,因為Parent
它是Child
.
實際上,您正在完全復制默認移動賦值運算子的行為(除了它不會檢查自賦值,如果您只轉發給其他賦值運算子,這是沒有意義的),這引出了一個問題,為什么你是完全定義它?只需遵循零規則,不要宣告移動賦值運算子。
這適用于Parent
' 和Child
' 移動賦值運算子。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/496816.html