相关疑难解决方法(0)

当它被绑定到调用函数中的const引用时,它的返回值的生命周期如何扩展到调用函数的范围?

"如果从函数返回一个值(不是引用),那么将它绑定到调用函数中的const引用,它的生命周期将扩展到调用函数的范围."

所以:案例A.

const BoundingBox Player::GetBoundingBox(void)
{
    return BoundingBox( &GetBoundingSphere() );
}
Run Code Online (Sandbox Code Playgroud)

const BoundingBox从函数返回类型的值GetBoundingBox()

变体I :(将它绑定到const引用)

const BoundingBox& l_Bbox = l_pPlayer->GetBoundingBox();
Run Code Online (Sandbox Code Playgroud)

变体II :(将它绑定到const副本)

const BoundingBox l_Bbox = l_pPlayer->GetBoundingBox();
Run Code Online (Sandbox Code Playgroud)

两者都工作正常,我没有看到l_Bbox对象超出范围.(虽然,我在变体1中理解,复制构造函数未被调用,因此稍微好于变体II).

另外,为了比较,我做了以下更改.

案例B

BoundingBox Player::GetBoundingBox(void)
{
    return BoundingBox( &GetBoundingSphere() );
}
Run Code Online (Sandbox Code Playgroud)

与变体:我

BoundingBox& l_Bbox = l_pPlayer->GetBoundingBox();
Run Code Online (Sandbox Code Playgroud)

和II:

BoundingBox l_Bbox = l_pPlayer->GetBoundingBox();
Run Code Online (Sandbox Code Playgroud)

该对象l_Bbox仍然没有超出范围.如何"将它绑定到调用函数中的const引用,它的生命周期将扩展到调用函数的范围",真正将对象的生命周期延长到调用函数的范围?

我在这里错过了一些小事吗?

c++ memory const pass-by-reference

9
推荐指数
2
解决办法
2587
查看次数

标签 统计

c++ ×1

const ×1

memory ×1

pass-by-reference ×1