[Development] FileRe: Move ctors for q_declare_shared types
Daniel Teske
Daniel.Teske at theqtcompany.com
Tue Jul 21 18:11:20 CEST 2015
Hi,
https://codereview.qt-project.org/#/c/120804/ and
https://codereview.qt-project.org/#/c/120771 do fix the move assignment
operators in Qt, just like I wanted.
I wonder why Marc Mutz didn't fell the need to update the mailing list on his
changed opinion and this fix.
Anyway, for those who don't want to read the full thread but want to know how
write a move assignment operator. This advice by Howard E. Hinnant is good:
"In general a move assignment operator should:
- Destroy visible resources (though maybe save implementation detail
resources).
- Move assign all bases and members.
- If the move assignment of bases and members didn't make the rhs resource-
less, then make it so."
In code this looks e.g. like this:
QVector<T> &operator=(QVector<T> &&other) Q_DECL_NOTHROW
{ QVector moved(std::move(other)); swap(moved); return *this; }
Now, if and only if the destructor of the class has no side effects or those
side effects are inconsequential, you might consider implementing move
assignment as a swap between other and this.
But if you are holding a user defined type or if you are holding resources like
file handlers or network sockets, you shouldn't implement move assignment via a
simple swap between other and this.
As a counter example, std::string's move assignment operator is allowed to be
implemented as a simple swap.
daniel
More information about the Development
mailing list