return value (not a reference) from the function, bound to a const reference in the calling function
Posted
by brainydexter
on Stack Overflow
See other posts from Stack Overflow
or by brainydexter
Published on 2010-04-10T21:58:04Z
Indexed on
2010/04/10
22:03 UTC
Read the original article
Hit count: 354
"If you return a value (not a reference) from the function, then bind it to a const reference in the calling function, its lifetime would be extended to the scope of the calling function."
So:
const BoundingBox Player::GetBoundingBox(void)
{
return BoundingBox( &GetBoundingSphere() );
}
Returns a value of type const BoundingBox from function GetBoundingBox()
Called function: (From within function Update() the following is called:) variant I: (Bind it to a const reference)
const BoundingBox& l_Bbox = l_pPlayer->GetBoundingBox();
variant II: (Bind it to a const copy)
const BoundingBox l_Bbox = l_pPlayer->GetBoundingBox();
Both work fine and I don't see the l_Bbox object going out of scope. (Though, I understand in variant one, the copy constructor is not called and thus is slightly better than variant II).
Also, for comparison, I made the following changes.
BoundingBox Player::GetBoundingBox(void)
{
return BoundingBox( &GetBoundingSphere() );
}
with Variants: I
BoundingBox& l_Bbox = l_pPlayer->GetBoundingBox();
and II:
BoundingBox l_Bbox = l_pPlayer->GetBoundingBox();
The objet l_Bbox still does not out scope. So, I don't see how "bind it to a const reference in the calling function, its lifetime would be extended to the scope of the calling function", really extends the lifetime of the object to the scope of the calling function ?
Am I missing something trivial here..please explain ..
Thanks a lot
© Stack Overflow or respective owner