Move语义在存在std:: Move时不使用

move semantics unused in presence of std::move

本文关键字:Move std 语义 存在      更新时间:2023-10-16

与以下内容:

#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() ?

Update:一般来说,是否有办法将左值引用强制转换为右值引用?

你有什么证据证明ifstream::operator=(const ifstream&)正在被调用?是否出现编译错误,提示正在调用此私有成员或已删除成员?

如果你的代码调用ifstream::operator=(const ifstream&),如果你的实现声称是c++ 11,那么这是你的c++ std::lib或编译器中的错误。当我编译你的代码时,ifstream::operator=(ifstream&&)被调用。这是我设计的

我在ifstream::operator=(ifstream&&)的实现中插入了一个print语句,只是为了确保。当我这样做时,你的程序打印出:

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

标准

 27.9.1.8 Assign and swap [ifstream.assign]
       basic_ifstream& operator=(basic_ifstream&& rhs);

我假设您正在查看错误的代码(无处保证基类操作符istream::operator=(istream&&) 必须被调用)?


Update:一般来说,是否有办法将左值引用强制转换为右值引用?

是的,这就是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;

做同样的事情,前提是move构造函数为nothrow。