c++ - 存在 std::move 时未使用移动语义

标签 c++ c++11 rvalue-reference noncopyable

具有以下内容:

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

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

最佳答案

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

如果您的代码正在调用 ifstream::operator=(const ifstream&),并且如果您的实现声称是 C++11,那么这是您的 C++ std::库,或编译器。当我编译你的代码时,ifstream::operator=(ifstream&&) 被调用。这是设计使然。

为了确定,我在 ifstream::operator=(ifstream&&) 的实现中插入了一条打印语句。当我完成你的程序打印出来时:

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

关于c++ - 存在 std::move 时未使用移动语义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8210204/

相关文章:

c++ - "Overload"基于函数对象operator()签名的函数模板

C++构造函数默认参数

c++ - 使用 std::move 函数签名传递 vector

c++ - 防止带有尾随返回类型的悬空右值引用

c++ - 我可以在基类方法中设置一个条件断点,仅当它是特定派生类的实例时才会触发?

c++ - c++什么时候分配/解除分配字符串文字

python - 指向引用的指针使用 ctypes

c++ - 为什么模板函数中的 std::is_array 不区分 int 和 array 类型?

c++ - 是否可以实现 std::move-and-clear 函数?

带有宏的 C++ 嵌套命名空间