Search code examples
c++c++14unique-ptrmove-semanticsrvalue-reference

Is it possible use an rvalue to initialize a data member?


I'm very new to r-value references and move semantics but the tutorials I've read have the attitude "since the temporary is a perfectly well constructed object that's usually copied and destroyed, why not extend its lifetime and move it around?"

So I'm picturing a scenario like this:

class Foo
{
  Foo m_foo; // Could also be a reference or a unique_ptr of any sort
public:
  Foo() {}
  Foo(Foo &&v_foo) { /*initialize m_foo using v_foo.*/ }

};

int main() 
{
  auto foo = std::make_unique<Foo>( Foo() );
  return 1;
}

Is anything like this possible?

Update: For clarification, what I mean when I say "initialize m_foo using v_foo" is I'd like to have m_foo point to or reference the v_foo object (the temporary created in main). Not copy/move its fields, but have it become the member.


Solution

  • You cannot keep a data member of type Foo inside class Foo because the object would be infinitely large (because each object of type Foo will have another Foo object inside, which that inner object will have another Foo object inside, and so on.

    With this change, you can have something like this:

    class Foo
    {
       std::unique_ptr<Foo> m_foo; 
    public:
       Foo() {}
       Foo(Foo &&v_foo) 
       { 
          m_foo = std::move(v_foo.m_foo); 
          v_foo.m_foo = nullptr;
       }
    
    };
    
    int main()
    {
       auto foo = std::make_unique<Foo>(Foo());
       return 0;
    }