Referencing Problem

An object of type std::string is to call its size() method and reference the returned variable:

&strIn.size()
or
&(strIn.size())

Why does this code produce this error:

error: lvalue required as unary '&' operand

size() should return a variable of type size_t, which I would think should be able to be referenced like any other variable.
Last edited on
closed account (1yR4jE8b)
No it can't. You would only be able to do that if the size() member function returned a reference to it's size member variable, but it only returns a copy.

The new C++0x standard will ratify this, however.
Last edited on
size_t is equivalent to a number (I can't remember if it was an unsigned int). So, you're taking a reference of a number, which you can't.

You should just use strIn.size ().
@yoonkwun: you'd have nothing to gain by using a reference there. The cost of copying an int or a similar type is slightly smaller than the cost of passing a reference. If you're interested: http://stackoverflow.com/questions/3009543/passing-integers-as-constant-references-versus-copying
My purpose is to write the variable returned by size() to a file. It would've been nice if I could do something like this:

fwrite(&strIn.size(), 4, 1, fileOut);

But I guess I'm left with no choice:

1
2
size_t temp = strIn.size();
fwrite(&temp, 4, 1, fileOut);
You could just use streams instead of the C library. It would be as simple as ofs << strIn.size();
except that outputs it as text, and not as binary.

The iostream version of outputting binary also requires a temp var.
Topic archived. No new replies allowed.