![](/img/trans.png)
[英]What happens when I make a assignment to object which has copy constructor but no assignment operator?
[英]How do I write move constructor and assignment operator for a class which has a private object as property?
我今天學會了移動構造器 。 我讀了這個答案 ,並嘗試將其中的move構造函數示例應用於我的代碼。
class UnicodeString
{
public:
enum ENDIANNESS_TYPE {LITTLE_ENDIAN = 0, BIG_ENDIAN = 1} ENDIANNESS;
bool REPLACE_NON_ASCII_CHARACTERS;
char REPLACE_NON_ASCII_CHARACTERS_WITH;
float VECTOR_RESERVE_COEFFICIENT;
UnicodeString(UnicodeString && Other);
// ...
UnicodeString & operator=(UnicodeString Other);
// ...
private:
std::vector<UnicodeChar> UString;
// ...
}
UnicodeString::UnicodeString(UnicodeString && Other)
{
this->REPLACE_NON_ASCII_CHARACTERS = Other.REPLACE_NON_ASCII_CHARACTERS;
this->REPLACE_NON_ASCII_CHARACTERS_WITH = Other.REPLACE_NON_ASCII_CHARACTERS_WITH;
this->VECTOR_RESERVE_COEFFICIENT = Other.VECTOR_RESERVE_COEFFICIENT;
this->ENDIANNESS = Other.ENDIANNESS;
this->UString = ?????
}
UnicodeString & UnicodeString::operator=(UnicodeString Other)
{
std::swap(?????, ?????);
return *this;
}
但是,與該示例不同,我的類UnicodeString
不僅僅包含一個簡單的C數組。 它包含一個std::vector<>
對象,其元素是我編寫的另一個類的實例。
首先,在move構造函數中,如何竊取 R-Value傳遞的另一個對象的UString
向量?
其次,在賦值運算符中,如何有效地交換主UnicodeString
對象的UString
引用和R-Value傳遞的引用? 注意, 。 UString
是一個私有屬性,因此不能從另一個對象直接訪問它
首先,在move構造函數中,如何竊取R-Value傳遞的另一個對象的UString向量?
只需move()
std::vector
move()
,因為它是可移動的( operator=(vector&&)
):
this->UString = std::move(Other.UString);
其次,在賦值運算符中,如何有效地交換主UnicodeString對象的UString引用和R-Value傳遞的UString引用? 請注意,UString是私有屬性,因此無法從另一個對象直接訪問它。
需要注意的是private
適用於class
,不給的實例class
。 意味着同一class
其他實例可以訪問另一個實例的private
成員。 因此,只需像以前一樣使用std::move(Other.UString)
。
這樣做的正確方法(假設您使用的是Visual Studio,因此編譯器不會為您完成此操作),它帶有初始化列表:
Unicode::UnicodeString(UnicodeString && other)
: this->REPLACE_NON_ASCII_CHARACTERS(other.REPLACE_NON_ASCII_CHARACTERS)
, this->REPLACE_NON_ASCII_CHARACTERS_WITH(other.REPLACE_NON_ASCII_CHARACTERS_WITH)
, this->VECTOR_RESERVE_COEFFICIENT(other.VECTOR_RESERVE_COEFFICIENT)
, this->ENDIANNESS(other.ENDIANNESS)
, this->UString(std::move(other.UString))
{
}
請注意,UString是私有屬性,因此無法從另一個對象直接訪問它。
誰說的? 私有意味着對象外部的代碼無法訪問它。 但是,一個對象實例最肯定可以訪問另一個對象實例的私有對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.