With reference to the following code, I do not understand why the move constructor is called both with an lvalue and rvalue. I would expect copy ctor to be printed when i pass an lvalue to the push method.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class my_obj
{
public:
my_obj()
{
cout << "default ctor\n";
}
my_obj(const my_obj& other)
{
cout << "copy ctor\n";
}
my_obj(my_obj&& other)
{
cout << "move ctor\n";
}
};
class test
{
private:
//my_obj arr[5];// array of my_obj
public:
template<typename T>
void push(T&& object)
{
print(forward<T>(object)); // should call the right overload
}
template<typename T>
void print(T&& a) //
{
cout << "move\n";
my_obj temp = forward<T>(a);
}
template<typename T>
void print(T& a)
{
cout << "val\n";
my_obj temp = forward<T>(a);
}
};
int main()
{
my_obj obj;
test f;
f.push(obj); // why is move ctor called here? shouldnt it be copy ctor since not rvalue
cout << "\nPUSHING TEMP\n\n";
f.push(my_obj {});
}
output:
default ctor
val
move ctor
PUSHING TEMP
default ctor
move
move ctor
Aucun commentaire:
Enregistrer un commentaire