![](/img/trans.png)
[英]C++11 constructor argument: std::move and value or std::forward and rvalue reference
[英]Why use std::forward rather than std::move for data member in rvalue reference constructor's initialization list?
我讀過這些材料:
std :: move和std :: forward之間有什么區別
這個答案非常接近我的問題,但一個是setImage
,另一個是rvalue引用構造函數,所以我擔心一些微妙的存在。
class ClassRoom
{
private:
vector<string> students;
public:
ClassRoom(vector<string>&& theStudents)
:students{std::forward<vector<string>>(theStudents)}
{
}
}
class ClassRoom
{
private:
vector<string> students;
public:
ClassRoom(vector<string>&& theStudents)
:students{std::move(theStudents)}
{
}
}
有人告訴我forward
是正確的方法,因為forward
一個用法是將rvalue引用變量傳遞給其他人並保證不再使用它。 但我無法弄清楚為什么不在這里使用move
,他說的是對的嗎?
在這個例子中, std::move
和std::forward
都做同樣的事情。
如果您將示例更改為推導類型,則會有所不同,例如
template<typename Arg>
ClassRoom(Arg&& theStudents)
:students{std::forward<Arg>(theStudents)}
{
}
VS
template<typename Arg>
ClassRoom(Arg&& theStudents)
:students{std::move(theStudents)}
{
}
然后:
vector<string> local_students = /* ... */;
ClassRoom cr(local_students)
Arg
推導出vector<string>&
,這意味着會發生不同的事情
向前:
forward<vector<string>&>
傳遞左值引用,因此所選的vector::vector
的重載是復制構造函數, local_students
不受影響
移動:
move<vector<string>&>
將左值引用轉換為rvalue-reference,因此所選的vector::vector
的重載是移動構造函數, local_students
現在處於移動狀態
我會在這里使用std::move
。 std::forward
旨在轉發通用引用。 在這種情況下沒有通用的參考。 雖然在這個例子中它沒有區別,但std::move
更簡潔,更自我記錄。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.