c++ - How do I write move constructor and assignment operator for a class which has a private object as property? -
i learned move constructors today. read this answer, , tried apply move constructor example in code.
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; }
however, unlike in example, class unicodestring
not merely contain simple c array. contains std::vector<>
object elements instances of class wrote.
first of all, in move constructor, how steal ustring
vector of other object passed r-value?
secondly, in assignment operator, how efficiently swap references of ustring
s of main unicodestring
object , 1 passed r-value? notice .ustring
private property, therefore cannot directly accessed object
first of all, in move constructor, how steal ustring vector of other object passed r-value?
just move()
std::vector
moveable (operator=(vector&&)
):
this->ustring = std::move(other.ustring);
secondly, in assignment operator, how efficiently swap references of ustrings of main unicodestring object , 1 passed r-value? notice ustring private property, therefore cannot directly accessed object.
note private
applies class
, not instance of class
. meaning other instances of same class
can access private
members of instance. so, use std::move(other.ustring)
before.
Comments
Post a Comment