gbadev.org forum archive

This is a read-only mirror of the content originally found on forum.gbadev.org (now offline), salvaged from Wayback machine copies. A new forum can be found here.

C/C++ > const MyClass& obj = MyClass (...) and lifetimes

#157388 - keldon - Fri May 23, 2008 9:19 am

Code:
const MyClass& obj = MyClass (1,2,3);
int m = obj.get_product() + obj.get_sum();


Not that I'm using this; but with optimisations and all, what is the worst that could/should happen? Apparently a const reference will extend the lifetime of the reference object to the lifetime of the const reference. I'm not too sure about that though and wanted some clarification on what the standards say.

#157411 - sajiimori - Fri May 23, 2008 9:43 pm

I found the standard a bit vague in that regard. These always worked for me:
Code:
MyClass returnsByValue();

const MyClass& ok1 = returnsByValue();
const MyClass& ok2 = MyClass(1, 2, 3);

This one gave me trouble on the compiler I use at work, though I'm not clear on whether it's supposed to work (edit: This actually works -- see below):
Code:
MyClass fn1();
MyClass fn2();
const MyClass& maybeNotOk = condition() ? fn1() : fn2();

And I'm also nervous about this one (edit: actually, this should really work):
Code:
ConvertibleToMyClass returnsConvertible();
const MyClass& dunno = returnsConvertible();

As far as performance, using this idiom is pretty much the strongest guarantee you can get that the number of copies will be minimized. In theory, using a value should work just as well, if the compiler is smart about return value optimizations.

Edit: The conditional operator example above caused a copy when I just tested it, but the copy was eliminated easily:
Code:
inline MyClass fn(bool b) { if(b) return fn1(); else return fn2(); }
const MyClass& noCopyHere = fn(condition());