Type conversion of reference to a temporary object

S

Stefan Strasser

JH said:
void foo(std::istream &in)
{
int i, j;
in >> i >> j;
} // foo


int main()
{
foo(std::istringstream("1 1"));
return 0;
} // main


g++ gives the following complaint when I attempt to compile this code:

error: invalid initialization of non-const reference of type
'std::istream &' from a temporary of type 'std::istringstream'

I was under the impression that my code above was standard-conforming.
Am I wrong on this point?

calling a constructor creates a temporary. temporaries are const. your
parameter of "foo" is not. you could pass it by value to make it work e.g.
since vs .net seems to be very standard conforming I guess this is some
sort of extension which can be turned off.
 
J

JH Trauntvein

I have something like the following code that I am trying to convert
from vs studio .net to g++ under linux:

#include <sstream>
#include <iostream>


void foo(std::istream &in)
{
int i, j;
in >> i >> j;
} // foo


int main()
{
foo(std::istringstream("1 1"));
return 0;
} // main


g++ gives the following complaint when I attempt to compile this code:

error: invalid initialization of non-const reference of type
'std::istream &' from a temporary of type 'std::istringstream'

I was under the impression that my code above was standard-conforming.
Am I wrong on this point?

Regards,

Jon Trauntvein
 
V

Victor Bazarov

JH said:
I have something like the following code that I am trying to convert
from vs studio .net to g++ under linux:

#include <sstream>
#include <iostream>


void foo(std::istream &in)
{
int i, j;
in >> i >> j;
} // foo


int main()
{
foo(std::istringstream("1 1"));
return 0;
} // main


g++ gives the following complaint when I attempt to compile this code:

error: invalid initialization of non-const reference of type
'std::istream &' from a temporary of type 'std::istringstream'

I was under the impression that my code above was standard-conforming.
Am I wrong on this point?

Yes. You create a temporary of type 'std::istringstream' in the main
function, and references to non-const cannot be bound to a temporary.
VC++ allows that as an extension. You will have to do

std::istringstream is("1 1");
foo(is);

V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,012
Latest member
RoxanneDzm

Latest Threads

Top