Returning a reference instead of a pointer
-
Ok, this could be a trivial question, but I'm becoming confused now. Imagine a write an instance method as the following:
@
QString aMethod(){
return QString( "Hello World" );
}
@such method builds an object on its stack, and then returns it. The caller can use the result as a reference (or at least assign it later to a reference). But is this correct? I mean, shouldn't the object be destructed as the method stack frame is released?
Moreover, it will be better and or possible to return a QString& (I found only examples on scalar reference returning).
If someone can help me understand and/or point to a good description of the problem it will be great!Thanks
-
The code you posted creates a QString on the stack, and returns a copy of it. If a reference were returned, it would be invalid because the original QString would have gone out of scope at the end of the aMethod() call.
-
Note that any decent compiler will optimize the copy away, though, so it is not as bad as it sounds.
-
Moreover, in addition of what mlong and Andre said, remember that Qt uses « Implicit Sharing » as an « optimization », which means that when a QString is copied, it only involves a pointer copy (pointer to some Data) and incremation of an atomic refcounter. This isn't free but it still does the job.
However, in such a case, decent compilers should optimize and avoid the copy, as Andre said. This is so called « Return Value Optimization (RVO) », see "here":http://en.wikipedia.org/wiki/Return_value_optimization
Doing this :
@
QString& aMethod(){
return QString( "Hello World" );
}
@is dangerous and will lead to an Undefined Behavior, since the QString on the stack will be destroyed at the end of the scope and thus the reference would become invalid (as stated by mlong).
@
QString *aMethod(){
return new QString( "Hello World" );
}
@This, is as bad as the previous example, since you'll have to explicitely remember to delete the memory if you don't wanna risk to leak memory (or you'll have to encapsulate the pointer into a Smart Pointer Class).
One thing to remember is that premature optimization is evil. So, let the compiler optimize such operations instead of going into an undefined behavior :) .
-
If you already familiar with c++11 then that r-value passing will be faster if QString had move semantics implemented.
-
As far as QString is concerned you don't have to worry about this, because QString is not copied, as octal said and I too remember(?) of reading something like this.
-
Copying a QString is indeed a fast operation, just copying a pointer and incrementing a counter. However, not copying is going to be even faster, of course.