I've read a lot about how the standard does not allow temporaries to be passed by non-const reference, but I could find anything convincing on why is that.
The usual argument I encounter is that it is unsafe because the lifetime of the value is unknown. But in reality it is not, it is bound to the function, whose parameter it is, and will remain "alive" until that function returns, so it is safe to use it inside that function, pass it to another function inside it and another... Basically as long as it is all synchronous execution, it should be safe, since the object will remain there until the first function receiving it returns.
What is the fundamental difference between the two approaches?
doSomething(createSomething());
{
something s = createSomething();
doSomething(s);
}
aside from the second one unnecessarily polluting the scope with an identifier for an object you will only use once.
The way I see it, the fact that it is a temporary only limits the potential to do damage, since it will no longer be used after that function call.
Can someone provide a snipped with what kind of bad things may happen in practice by passing a temporary by reference?
Also, my question is strictly pre-c++11, so rvalue references are outside its scope.
EDIT: From the linked question, sbi's answer:
// this doesn't compile:
g(getx()); // g() would modify an object without anyone being able to observe
But that implies that the only reason one would ever pass something by reference is to be able to observe changes made in that function after it has returned. Now, OBVIOSLY, if you use a temporary it goes without saying this is not part of your intent, nor is the reason just mentioned the only reason one would pass by reference. Which is why the scope of that question is not the same as the one labeled duplicate. You are just as likely to pass by reference to avoid a costly copy and your design can involve use of that object which is entirely encapsulated within that function and functions called within.
That other question focuses on one use of pass by reference and doesn't explain what could go wrong, nor does it take into consideration the very fact that using a temporary negates that one concern the answers address. It basically answers "because it would modify an object without anyone being able to observe", which is rightfully presented as pointless, but which is CLEARLY not the intent when you use a temporary in the first place.
To put it in other words, the answer says "You can't do it, because you can't observe the changes when you don't want to observe the changes"... DO'H How can the limitation be the inability to do something you clearly don't want to do?
answerquestion, provided that the OP points out exactly *what* isn't convincing / what is missing from the existing answers. Maybe this could also be a comment to a specific answer. – dyp Dec 13 '14 at 23:08