2011-11-21 30 views
2

下列要求:移動語義閒置性病的存在::移動

#include <iostream> 
#include <fstream> 
using namespace std; 
int main() { 
    ifstream f; 
    ifstream g; 
    f = std::move(g); 
} 

爲什麼ifstream::operator=(const ifstream&)被調用,而不是ifstream::operator=(ifstream& &)即使std::move()叫?

更新:一般來說,有沒有辦法將左值引用強制爲右值引用?

+2

'istream :: operator =(istream &&)'是否存在? – iammilind

+0

@iammilind看到sehe的回答。 – moshbear

+0

@iammilind:是的,但它是受保護的(請參閱第27.7.2.1.2節basic_istream賦值和交換) – sehe

回答

5

你有什麼證據可以呼叫ifstream::operator=(const ifstream&)?你是否遇到編譯錯誤,說你正在調用這個私人或刪除的成員?

如果您的代碼調用了ifstream::operator=(const ifstream&),並且您的實現聲明爲C++ 11,那麼這是您的C++ std :: lib或編譯器中的一個錯誤。當我編譯你的代碼時,ifstream::operator=(ifstream&&)被調用。這是設計。

我堅持在我的實施ifstream::operator=(ifstream&&)打印聲明只是爲了確保。當我的程序打印出來時:

basic_ifstream<_CharT, _Traits>::operator=(basic_ifstream&& __rhs) 
+0

然後,看起來像這個相當煩人的bug已經在gcc一段時間了。打開錯誤報告的時間。 – moshbear

+0

另外,你使用了哪種編譯器? – moshbear

+0

對不起,由於'basic_ifstream <_CharT,_Traits> :: operator =(basic_ifstream && __rhs)'甚至沒有被定義,所以這不是一個gcc錯誤,而是一個libstdC++錯誤。 – moshbear

1

標準

27.9.1.8 Assign and swap [ifstream.assign] 

     basic_ifstream& operator=(basic_ifstream&& rhs); 

我假定你正在尋找在錯誤的代碼(無處它保證了基類運營商istream::operator=(istream&&)必須調用)?


更新:一般來說,有沒有辦法強迫一個左值引用到右值引用?

是的,它是什麼呢std::move

template <class T> typename remove_reference<T>::type&& move(T&& t) noexcept; 

還有

template <class T> typename conditional< 
    !is_nothrow_move_constructible<T>::value && is_copy_constructible<T>::value, 
    const T&, T&&>::type move_if_noexcept(T& x) noexcept; 

這不相同,前提是moveconstructor是拋出異常。

+0

我忘記了它是否具有'MoveAssignable'的基類或派生類。編輯的問題。 – moshbear