By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,750 Members | 1,214 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,750 IT Pros & Developers. It's quick & easy.

Type conversion of reference to a temporary object

P: n/a
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

Jul 23 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
JH Trauntvein wrote:
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
Jul 23 '05 #2

P: n/a
JH Trauntvein schrieb:
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.
Jul 23 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.