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()被调用?

更新:一般来说,有没有办法将左值引用强制为右值引用?

4

2 回答 2

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)
于 2011-11-21T15:20:30.690 回答
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 是 nothrow ,那么它也是一样的。

于 2011-11-21T10:23:02.777 回答