Trying to understand the difference between rvalue formal parameter and call by value parameter.
When I called fun(move(Demo{}) I see only default constructor called once. While I called gun(move(Demo{}) I see default constructor and rval constructor called. Please some one help me to understand the behaviour of && formal argument type, uses of && in functions/member functions.
compilers clang++ , g++ , vc++
#include <iostream>
#include <utility>
#include <type_traits>
using namespace std;
class Demo {
int i = 10;
public:
Demo(){
i = 40;
}
Demo(Demo && p) {
i = p.i + 20;
cout << "I am in Demo && " << endl;
}
Demo & operator = (Demo & p) {
cout << "I am in operator && " << endl;
}
Demo & operator = (Demo && p) {
i = p.i + 10;
cout << "I am in operator && " << endl;
}
~Demo(){
cout << "I am in ~Demo " << i << endl;
}
};
void fun(Demo & d) {
cout << "fun( &) " << endl;
cout << " -- End -- " << endl;
}
void fun(Demo && d) {
cout << "fun( && ) " << endl;
std::cout << std::boolalpha;
cout << "Lvalur reference : " << is_lvalue_reference<decltype(d)>::value << endl;
cout << "Rvalue Refernce : " << is_rvalue_reference<decltype(d)>::value << endl;
cout << " -- End -- " << endl;
}
void gun(Demo d) {
cout << "gun( ) " << endl;
std::cout << std::boolalpha;
cout << "Lvalur reference : " << is_lvalue_reference<decltype(d)>::value << endl;
cout << "Rvalue Refernce : " << is_rvalue_reference<decltype(d)>::value << endl;
cout << " -- End -- " << endl;
}
int main() {
cout << "Main begin " << endl;
fun(move(Demo{}));
cout << "------------------- " << endl;
gun(move(Demo{}));
cout << "Main End " << endl;
}
//Output
Main begin fun( && ) Lvalur reference : false Rvalue Refernce : true -- End -- I am in ~Demo 40 ------------------- I am in Demo && gun( ) Lvalur reference : false Rvalue Refernce : false -- End -- I am in ~Demo 60 I am in ~Demo 40 Main End
Aucun commentaire:
Enregistrer un commentaire