Reputation: 10243
I'm implementing a move constructor and need to initialize other back to it's original state, as implemented in the default constructor. Is this possible or do I need to duplicate the code?
class Class
{
Class() { /* code to duplicate */ }
Class(Class&& other) :
mMember(other.mMember) {
other.Class(); // code to duplicate?
}
};
I know other.Class() is invalid here and I know that constructors can call each other with C++11 now.
Upvotes: 2
Views: 375
Reputation: 41820
The best way would be to reassign it. Since the object is already constructed, it would be a mistake to call the constructor again.
However, you can create an instance and call the assignement operator:
Class(Class&& other) noexcept : mMember(std::move(other.mMember)) {
other = Class{};
}
Another way would be to default construct your class and swap values with the old one:
Class(Class&& other) noexcept {
std::swap(mMember, other.mMember);
}
If you really need other
to take the value it would from calling the default constructor, you can do this:
Class(Class&& other) noexcept : Class() {
std::swap(mMember, other.mMember);
}
It will call the default constructor in the new object and then swap the values from the other
object.
Upvotes: 4