參照以下代碼,我不明白爲什麼move constructor
被稱爲lvalue
和rvalue
。我希望copy ctor
打印時,我通過lvalue
到push
方法。正向參照混淆
#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
{
public:
template<typename T>
void push(T&& object)
{
print(forward<T>(object));
}
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 {});
}
輸出:
default ctor
val
move ctor
PUSHING TEMP
default ctor
move
move ctor
@pyjg沒有理由感到愚蠢。每個人都必須在某個時候學習。 – Barry
所以正確的修復將是'my_obj temp = a;'在那個函數中? – PYA
@pyjg是的。轉發的目的是保留值類別,但在這裏我們知道我們有一個左值。通常情況下,您只想「轉發」轉發引用 - 而您沒有轉發引用,因此請勿轉發。 (「正確的」轉發將是'轉發(a)',但請不要寫這些)。 –
Barry