Lvalue link constructor is called instead of rvalue link constructor

There is this code:

#include <iostream>

class F {
public:
   F() = default;
   F(F&&) {
      std::cout << "F(F&&)" << std::endl;
   }
   F(F&) {
      std::cout << "F(F&)" << std::endl;
   }
};

class G {
   F f_;
public:
   G(F&& f) : f_(f) {
      std::cout << "G()" << std::endl;
   }
};

int main(){
   G g = F();
   return 0;
}

Conclusion:

F(F&)
G()

Why is the constructor F(F&)called instead of the constructor F(F&&)in the class constructor G? The parameter for the class constructor Gis F&& f, which is the rvalue reference, and the constructor for the lvalue reference is called.

+5
source share
1 answer

Why is the constructor F (F &) called instead of the constructor F (F &) in the constructor of class G?

f lvalue. , rvalue, - rvalue f, . lvalue. , .

lvalue , lvalue. , :

class G {
    F f_;
public:
    G(F&& f) : f_(std::move(f)) {
       std::cout << "G()" << std::endl;
    }
};

std::forward<>(), , f :

class G {
    F f_;
public:
    G(F&& f) : f_(std::forward<F>(f)) {
       std::cout << "G()" << std::endl;
    }
};

, lvalues ​​ rvalues ​​ f f:

class G {
    F f_;
public:
    template<typename F>
    G(F&& f) : f_(std::forward<F>(f)) {
       std::cout << "G()" << std::endl;
    }
};

, , G :

F f;
G g(f); // Would not be possible with a constructor accepting only rvalues

: -, , , :

class G {
    F f_;
public:
    template<typename F>
    G(F&& f) : f_(std::forward<F>(f)) {
       std::cout << "G()" << std::endl;
    }
    G(G const&) = default;
    G(G&); // Must be defaulted out-of-class because of the reference to non-const
};

G::G(G&) = default;

, , , , G G. , , . .

+9

All Articles