“如果你从函数返回一个值(不是引用),然后将它绑定(bind)到调用函数中的 const 引用,它的生命周期将扩展到调用函数的范围。”
所以:案例 A
const BoundingBox Player::GetBoundingBox(void)
{
return BoundingBox( &GetBoundingSphere() );
}
从函数 GetBoundingBox()
const BoundingBox
类型的值
变体 I:(将其绑定(bind)到 const 引用)
const BoundingBox& l_Bbox = l_pPlayer->GetBoundingBox();
变体 II:(将其绑定(bind)到 const 拷贝)
const BoundingBox l_Bbox = l_pPlayer->GetBoundingBox();
两者都工作正常,我没有看到 l_Bbox
对象超出范围。 (虽然,我理解在变体一中,复制构造函数没有被调用,因此比变体 II 略好)。
另外,为了比较,我做了以下更改。
案例 B
BoundingBox Player::GetBoundingBox(void)
{
return BoundingBox( &GetBoundingSphere() );
}
带有变体: 我
BoundingBox& l_Bbox = l_pPlayer->GetBoundingBox();
和二:
BoundingBox l_Bbox = l_pPlayer->GetBoundingBox();
对象 l_Bbox
仍然没有超出范围。 “将它绑定(bind)到调用函数中的 const 引用,它的生命周期会扩展到调用函数的范围”,如何真正将对象的生命周期扩展到调用函数的范围?
我在这里错过了一些琐碎的事情吗?
最佳答案
通常一个临时对象(例如由函数调用返回的对象)的生命周期会延伸到“封闭表达式”的末尾。但是,临时绑定(bind)到引用通常会将其生命周期“提升”到引用的生命周期(可能是也可能不是调用函数的生命周期),但也有一些异常(exception)。 12.2/5“临时对象”中的标准涵盖了这一点:
The temporary to which the reference is bound or the temporary that is the complete object to a subobject of which the temporary is bound persists for the lifetime of the reference except as specified below. A temporary bound to a reference member in a constructor’s ctor-initializer (12.6.2) persists until the constructor exits. A temporary bound to a reference parameter in a function call (5.2.2) persists until the completion of the full expression containing the call.
有关详细信息,请参阅以下内容:
- C++ constant reference lifetime (container adaptor)
- GotW #88: A Candidate For the "Most Important const"
一个可能有助于可视化正在发生的事情的示例:
#include <iostream>
#include <string>
class foo {
public:
foo( std::string const& n) : name(n) {
std::cout << "foo ctor - " << name + " created\n";
};
foo( foo const& other) : name( other.name + " copy") {
std::cout << "foo copy ctor - " << name + " created\n";
};
~foo() {
std::cout << name + " destroyed\n";
};
std::string getname() const { return name; };
foo getcopy() const { return foo( *this); };
private:
std::string name;
};
std::ostream& operator<<( std::ostream& strm, foo const& f) {
strm << f.getname();
return strm;
}
int main()
{
foo x( "x");
std::cout << x.getcopy() << std::endl;
std::cout << "note that the temp has already been destroyed\n\n\n";
foo const& ref( x.getcopy());
std::cout << ref << std::endl;
std::cout << "the temp won't be deleted until after this...\n\n";
std::cout << "note that the temp has *not* been destroyed yet...\n\n";
}
其中显示:
foo ctor - x created
foo copy ctor - x copy created
x copy
x copy destroyed
note that the temp has already been destroyed
foo copy ctor - x copy created
x copy
the temp won't be deleted until after this...
note that the temp has *not* been destroyed yet...
x copy destroyed
x destroyed
关于c++ - 当它绑定(bind)到调用函数中的 const 引用时,它的返回值的生命周期如何扩展到调用函数的范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2615162/