Why C++ allows returning ifstream object?

232 Views Asked by At

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?

1

There are 1 best solutions below

0
On BEST ANSWER

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.