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:
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
6 replies
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 [en.wikipedia.org]
Doing this :
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).
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 :) .
You must log in to post a reply. Not a member yet? Register here!




