On 1 Dez., 20:52, eca <enrico.ecam...@gmail.com> wrote:
(...)
What I know is that temporaries can be passed as const references
and that VC allows passing them as non-const references as an
extension to the standard.
What I don't know precisely is whether there is any potential risk
of error in doing as above.
Could you help me understand the rationale of the two approaches?
The reason why standard C++ decided the rules is to provide
a safety belt for you: Usually an object addressed per mutable
lvalue reference as above is supposed to modify this thingee
and that this changed state in this thingee can be evaluated
later. Now consider the following example, which was the
showstopper for allowing rvalues (like temporaries) to be
acceptable arguments for lvalue-references:
void inc(int& arg) { arg++; }
typedef long MyInt;
int main() {
MyInt i = 0;
inc(i);
if (i == 1) {
// Life-saving logic
}
}
Should this program be well-formed? If yes, how do you
estimate the chances, that this kind of *error* - hidden
in some complex software, will be finally found and fixed?
What happens in my example is that i is converted into
a *temporary* of type int, which is the actual argument
of inc. So, the seemingly induced change i never happens,
because *only* the temporary itself is modified here!