I have a class with a const member that needs both a move constructor and assignment.
I implemented it the following way:
struct C
{
const int i;
C(int i) : i{i} {}
C(C && other) noexcept: i{other.i} {}
C & operator=(C && other) noexcept
{
//Do not move from ourselves or all hell will break loose
if (this == &other)
return *this;
//Call our own destructor to clean-up before moving
this->~C();
//Use our own move constructor to do the actual work
new(this) C {std::move(other)};
return *this;
}
//Other stuff here (including the destructor)....
}
This compiles and works as expected.
The question is whether this is the normal way to implement such a move assignment or there is a less contrived way to do it?
Aucun commentaire:
Enregistrer un commentaire