Temporary non-const istream reference in constructor (C++)
- by Christopher Bruns
It seems that a constructor that takes a non-const reference to an istream cannot be constructed with a temporary value in C++.
#include <iostream>
#include <sstream>
using namespace std;
class Bar
{
public:
explicit Bar(std::istream& is) {}
};
int main()
{
istringstream stream1("bar1");
Bar bar1(stream1); // OK on all platforms
// compile error on linux, Mac gcc; OK on Windows MSVC
Bar bar2(istringstream("bar2"));
return 0;
}
This compiles fine with MSVC, but not with gcc. Using gcc I get a compile error:
g++ test.cpp -o test
test.cpp: In function ‘int main()’:
test.cpp:18: error: no matching function for call to ‘Bar::Bar(std::istringstream)’
test.cpp:9: note: candidates are: Bar::Bar(std::istream&)
test.cpp:7: note: Bar::Bar(const Bar&)
Is there something philosophically wrong with the second way (bar2) of constructing a Bar object? It looks nicer to me, and does not require that stream1 variable that is only needed for a moment.