reference - How to "return an object" in C++? -


i know title sounds familiar there many similar questions, i'm asking different aspect of problem (i know difference between having things on stack , putting them on heap).

in java can return references "local" objects

public thing calculatething() {     thing thing = new thing();     // calculations , modify thing     return thing; } 

in c++, similar have 2 options

(1) can use references whenever need "return" object

void calculatething(thing& thing) {     // calculations , modify thing } 

then use this

thing thing; calculatething(thing); 

(2) or can return pointer dynamically allocated object

thing* calculatething() {     thing* thing(new thing());     // calculations , modify thing     return thing; } 

then use this

thing* thing = calculatething(); delete thing; 

using first approach won't have free memory manually, me makes code difficult read. problem second approach is, i'll have remember delete thing;, doesn't quite nice. don't want return copied value because it's inefficient (i think), here come questions

  • is there third solution (that doesn't require copying value)?
  • is there problem if stick first solution?
  • when , why should use second solution?

i don't want return copied value because it's inefficient

prove it.

look rvo , nrvo, , in c++0x move-semantics. in cases in c++03, out parameter way make code ugly, , in c++0x you'd hurting using out parameter.

just write clean code, return value. if performance problem, profile (stop guessing), , find can fix it. won't returning things functions.


that said, if you're dead set on writing that, you'd want out parameter. avoids dynamic memory allocation, safer , faster. require have way construct object prior calling function, doesn't make sense objects.

if want use dynamic allocation, least can done put in smart pointer. (this should done time anyway) don't worry deleting anything, things exception-safe, etc. problem it's slower returning value anyway!


Comments

Popular posts from this blog

IF statement in MySQL trigger -

c++ - What does MSC in "// appease MSC" comments mean? -

javascript - Blogger related post gadget image Resize s72-c [ Need Expert Help ] -