2016-03-06 49 views
1

「理論」問題,如果你願意。C++我總是必須使用std :: move來調用移動構造函數嗎?

爲了在類中執行/使用移動構造函數,我總是必須使用std::move(...)來告訴編譯器,我希望「移動」一個對象而不是複製它嗎?

是否有任何情況下編譯器會調用移動構造函數而不使用std::move? (我的猜測是在函數返回值?)

+0

IIRC,拋出異常是另一個例子 –

+0

@PiotrSkotnicki你能解釋更多的細節? – user3728501

回答

3

根據cppreference.com(http://en.cppreference.com/w/cpp/language/move_constructor):

每當物體被從相同類型的x值,其包括

初始化此舉構造函數被調用
  • 初始化,T a = std :: move(b);或T a(std :: move(b));其中b是類型T;
  • 函數參數傳遞:f(std :: move(a));其中a是T類型,f是void f(T t);
  • 函數return:return a;在T f()這樣的函數內部,其中a是具有移動構造函數的T類型。

在大多數情況下,是std::move是必要的。

+0

啊,但不是函數返回?我的猜測是正確的? – user3728501

+0

@ user3728501如果我明白你在問什麼,看起來編譯器會自動調用移動構造函數。 –

+0

ie;如果我在一個函數中構造一個std :: vector並返回這個向量,這與return std :: move(v)相同; v是那個向量? – user3728501

2

編譯器將調用移動的構造,而不std::move時:

  • 由值
  • 從相同類型的右值構造一個對象時

返回一個局部變量在所有其他例如,使用std::move。例如: -

struct S { 
    std::string name; 
    S(std::string name) : name(std::move(name)) {} 
}; 

std::unique_ptr<Base> func() { 
    auto p = std::make_unique<Derived>(); 
    return std::move(p); // doesn't work without std::move 
} 
+0

很清楚謝謝! – johnbakers

1

std::move只是一個演員。

unique_ptr<int> global; 

auto v = unique_ptr<int>(global); // global is a lvalue, therefore the 
unique_ptr(unique_ptr<T>&v) constructor that accepts lvalue references is called. 

auto v = unique_ptr<int>(std::move(global)); // move returns a &&rvalue reference, therefore the 
unique_ptr(unique_ptr<T>&&v) constructor that accepts &&rvalue references is used. 

當的複製操作的省音滿足準則和要複製是由一個左值所指定的對象,過載分辨率選擇用於拷貝首先執行彷彿構造對象被指定爲右值

因此

unique_ptr<int> hello() 
{ 
    unique_ptr<int> local; 
    return local; 

    // local is an lvalue, but since the critera for elision is met, 
    // the returned object is created using local as if it was an rvalue 
} 

此外,

unique_ptr<int> hello = std::unique_ptr<int>(); 
// we have a pure rvalue in the right, therefore no std::move() cast is needed. 
相關問題