In C++98, the following code does not compile because the ifstream has no copy constructor:
#include <iostream>
#include <fstream>
using namespace std;
ifstream f() {
return ifstream("main.cpp");
}
int main() {
ifstream st= f();
}
However using multiple GCC versions with C++11, this compiles without warnings. What is the reason of this?
C++11 added move constructors. The stream is now moved. The source object here is a temporary in the return expression, which can be moved to the st
object in main
.