When creating a temporary object in a scope, the compiler doesn't see the provided argument to the constructor and gives a compiling error.
As in the following example:
#include <sstream>
#include <iostream>
class csventry
{
public:
csventry(std::ostream& ostream) :
_ostream(ostream)
{}
~csventry()
{ _ostream << std::endl; }
csventry& operator << (const std::string& value) {
_ostream << ", ";
_ostream << value;
return *this;
}
private:
std::ostream& _ostream;
};
int main ()
{
std::ostringstream log;
{ csventry(log) << "User Log-on:"; }
{ csventry(log); }
{ csventry(log) << "Summary:"; }
std::cout<<log.str()<<std::endl;
}
I get this error.
main.cpp: In function ‘int main()’:
main.cpp:29:16: error: no matching function for call to ‘csventry::csventry()’
{ csventry(log); }
^
main.cpp:7:2: note: candidate: csventry::csventry(std::ostream&)
csventry(std::ostream& ostream) :
^~~~~~~~
main.cpp:7:2: note: candidate expects 1 argument, 0 provided
main.cpp:4:7: note: candidate: constexpr csventry::csventry(const csventry&)
class csventry
^~~~~~~~
main.cpp:4:7: note: candidate expects 1 argument, 0 provided
Tried with gcc 7.3 and 5.4
It worked when I name the temporary object, { csventry entry(log); }
Why does the compiler miss the provided argument?