Suppose I have an instantiated Base b
. Foo
is a child class of Base
.
What I want to do is to have the constructor for a Foo
class Foo : public Base
{
Foo(Base b, T otherArg) : Base(b)
{
/*ToDo - do something with otherArg*/
}
}
move the 'b' instance to the instance of Foo
being constructed. If the construction of Foo
fails (e.g. in my /*ToDo step*/
) then b
should not be moved.
Can I do this in C++11? (I cannot afford to take a deep copy). Does the constructor prototype need to be Foo(Base&& b, T otherArg)
?
Yes you can :
Base
class so rvalues are acceptedstd::move
Example:
#include <iostream>
#include <utility>
class Base
{
public:
Base() {}
Base(Base&& b) { std::cout << "Move ctr"; }
};
class Foo : public Base
{
public:
Foo(Base&& b, double otherArg) : Base(std::move(b))
{
// ...
}
};
int main()
{
Foo(Base(), 2.0);
}
Or
int main()
{
Base b;
Foo(std::move(b), 2.0);
}
Note:
b
in Base(Base&& b)
(before doing anything with it, of course), and restore it through a rollback_move
member function in case of an exception in the Foo
constructor. Live demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With