The correctness of the code you write should never depend on an optimization. It should output the correct result when executed on the C++ "virtual machine" that they use in the specification.
However, what you talk about is more of an efficiency sort of question. Your code runs better if optimized with a RVO optimizing compiler. That's fine, for all the reasons pointed out in the other answers.
However, if you require this optimization (such as if the copy constructor would actually cause your code to fail), now you're at the whims of the compiler.
I think the best example of this in my own practice is tail call optimization:
int sillyAdd(int a, int b)
{
if (b == 0)
return a;
return sillyAdd(a + 1, b - 1);
}
It's a silly example, but it shows a tail call, where a function is called recursively right at the end of a function. The C++ virtual machine will show that this code operates properly, though I may cause a little confusion as to why I bothered writing such an addition routine in the first place. However, in practical implementations of C++, we have a stack, and it has limited space. If done pedantically, this function would have to push at least b + 1
stack frames onto the stack as it does its addition. If I want to calculate sillyAdd(5, 7)
, this is not a big deal. If I want to calculate sillyAdd(0, 1000000000)
, I could be in real trouble of causing a StackOverflow (and not the good kind).
However, we can see that once we reach that last return line, we're really done with everything in the current stack frame. We don't really need to keep it around. Tail call optimization lets you "reuse" the existing stack frame for the next function. In this way, we only need 1 stack frame, rather than b+1
. (We still have to do all those silly additions and subtractions, but they don't take more space.) In effect, the optimization turns the code into:
int sillyAdd(int a, int b)
{
begin:
if (b == 0)
return a;
// return sillyAdd(a + 1, b - 1);
a = a + 1;
b = b - 1;
goto begin;
}
In some languages, tail call optimization is explicitly required by the specification. C++ is not one of those. I cannot rely on C++ compilers to recognize this tail call optimization opportunity, unless I go case-by-case. With my version of Visual Studio, the release version does the tail call optimization, but the debug version does not (by design).
Thus it would be bad for me to depend on being able to calculate sillyAdd(0, 1000000000)
.