Move constructors and inheritance

前端 未结 2 562
温柔的废话
温柔的废话 2021-01-01 17:54

I am trying to understand the way move constructors and assignment ops work in C++11 but I\'m having problems with delegating to parent classes.

The code:

         


        
2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-01 18:29

    You're only ever calling your base class's stuff with lvalues:

    void foo(int&){}  // A
    void foo(int&&){} // B
    
    void example(int&& x)
    {
        // while the caller had to use an rvalue expression to pass a value for x,
        // since x now has a name in here it's an lvalue:
        foo(x); // calls variant A
    }
    
    example(std::move(myinteger)); // rvalue for us, lvalue for example
    

    That is, you need:

    T(T&& o):
    T0(std::move(o)) // rvalue derived converts to rvalue base
    {
        puts("move");
    }
    

    And:

    T& operator=(T&& o)
    {
        puts("move assign");
    
        T0::operator=(std::move(o)));
    
        return *this;
    }
    

提交回复
热议问题