Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using move semantics to push a base class instance into a child class instance

Tags:

c++

c++11

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)?

like image 537
P45 Imminent Avatar asked Oct 31 '22 18:10

P45 Imminent


1 Answers

Yes you can :

  • Declare a move constructor for the Base class so rvalues are accepted
  • Move the base argument with std::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:

  • As for the rollback in case of an exception, you can still save the state of 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

like image 180
quantdev Avatar answered Nov 15 '22 05:11

quantdev