Is there a difference between this:
MyClass c = getMyClass();
calculate(c.value);
and this:
calculate(getMyClass().value);
in the scope of performance and memory allocation?
Is there a difference between this:
and this:
in the scope of performance and memory allocation? |
|||
migrated from programmers.stackexchange.com Jun 27 at 4:29This question came from our site for professional programmers interested in conceptual questions about software development. |
|||
Yes, there is a fairly serious difference. In the first case, In the second case, the compiler cleans up the temporary right away, so all resources are released promptly, and it being an rvalue gives the compiler more freedom to optimize and permits move semantics. This is still true when You should always scope objects to the minimum scope required, and if you don't need to access |
|||||
|
Is there a difference? Yes, massively so. To the reader. The compiler couldn't care less which way you write it. The code emitted, space used and time of execution are so close they're not worth spending one millisecond of thinking time on. But your readers will care. In some situations the first form offers the opportunity to provide a useful variable name to help explain your intent. In other situations the lack of a declared variable makes it a single statement and could be easier to read, especially if there are lots of them. Please, get over the idea you should care about what the compiler thinks and start to care more about what your readers think! And, by the way, you are one of those readers in six month's time. |
|||||
|
Nope! It merely evaluates the |
|||||||||||||
|
The first form tells the compiler to create a new instance of
Even if As has already been pointed out, the instance created by the first form continues to exist until the end of the scope, although you can minimize the effect in this case by adding an extra pair of
Personally, in most cases I prefer to create a local variable with a name that tells me something about what I'm passing to the |
|||||||||||||||||||||
|
getMyClass
returns a reference the first invokes the copy constructor (RVO non withstanding) but the latter doesn't. – delnan Jun 24 at 6:19value()
, while the second example usesvalue
. – Jace Browning Jun 24 at 15:26