Search code examples
c++c++11rvalue-referencenoncopyable

move semantics unused in presence of std::move


With the following:

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

Why is ifstream::operator=(const ifstream&) being called instead of ifstream::operator=(ifstream&&) even though std::move() is called?

Update: Generally speaking, is there a way to coerce a lvalue reference to a rvalue reference?


Solution

  • What evidence do you have that ifstream::operator=(const ifstream&) is being called? Do you get a compile error that says you're calling this private or deleted member?

    If your code is calling ifstream::operator=(const ifstream&), and if your implementation is claiming to be C++11, then this is a bug in either your C++ std::lib, or compiler. When I compile your code, ifstream::operator=(ifstream&&) gets called. And this is by design.

    I stuck a print statement in my implementation of ifstream::operator=(ifstream&&) just to be sure. When I did your program prints out:

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