Move语义在存在std:: Move时不使用
move semantics unused in presence of std::move
与以下内容:
#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。
相关文章:
- Usages of std::move
- 在C++中对T*类型执行std::move的意外行为
- 关于std::move的使用,是否有编译警告
- 我应该实现右值推送功能吗?我应该使用std::move吗
- 通过实例理解std::move及其目的
- 返回一个带有 std::move 的对象并链接函数
- '[](std::list& list)<int>{return std::move(list)}(list)' 是否保证将 'list' 留空?
- 当 std::move 与 C 样式数组或不移动对象时会发生什么
- 为什么当我为 for(auto& it : myUnorderedMap) {... = std::move(it.second)} 时,我会得到一个 const 引用?
- std::move a const std::vector in a lambda capture
- "std::forward"和"std::move"真的不生成代码吗?
- std::vector move 而不是交换到空 vector 并释放存储
- 是否有必要使用 std::move?这不是已经是一个右值参考了吗?
- 如何在没有 std::move 的情况下移动临时对象
- 关于在成员重载中使用 std::move() 的问题
- 显式清除 std::move 之后的源资源
- std::move(key) 同时迭代unordered_map<字符串,字符串>?
- std::move(std::array) g++ vs visual-c++
- 使用 move std::string 的 .data() 成员不适用于小字符串?
- std::move(std::unique_ptr()) 组合是否有标准缩写