Returning object from function
Posted
by brainydexter
on Stack Overflow
See other posts from Stack Overflow
or by brainydexter
Published on 2010-04-11T05:09:23Z
Indexed on
2010/04/11
5:13 UTC
Read the original article
Hit count: 286
I am really confused now on how and which method to use to return object from a function. I want some feedback on the solutions for the given requirements.
Scenario A: The returned object is to be stored in a variable which need not be modified during its lifetime. Thus,
const Foo SomeClass::GetFoo() {
return Foo();
}
invoked as:
someMethod() {
const Foo& l_Foo = someClassPInstance->GetFoo();
//...
}
Scneraio B: The returned object is to be stored in a variable which will be modified during its lifetime. Thus,
void SomeClass::GetFoo(Foo& a_Foo_ref) { a_Foo_ref = Foo(); }
invoked as: someMethod() { Foo l_Foo; someClassPInstance->GetFoo(l_Foo); //... }
I have one question here: Lets say that Foo cannot have a default constructor. Then how would you deal with that in this situation, since we cant write this anymore:
Foo l_Foo
Scenario C: Foo SomeClass::GetFoo() { return Foo(); }
invoked as:
someMethod() {
Foo l_Foo = someClassPInstance->GetFoo();
//...
}
I think this is not the recommended approach since it would incur constructing extra temporaries.
What do you think ? Also, do you recommend a better way to handle this instead ?
© Stack Overflow or respective owner