“如果从函数返回一个值(而不是引用),然后将其绑定到调用函数中的 const 引用,则其生命周期将扩展到调用函数的范围。”
所以:情况A
const BoundingBox Player::GetBoundingBox(void)
{
return BoundingBox( &GetBoundingSphere() );
}
返回类型的值const BoundingBox
从函数GetBoundingBox()
变体 I:(将其绑定到 const 引用)
const BoundingBox& l_Bbox = l_pPlayer->GetBoundingBox();
变体 II:(将其绑定到 const 副本)
const BoundingBox l_Bbox = l_pPlayer->GetBoundingBox();
两者都工作正常,但我没有看到l_Bbox
对象超出范围。 (不过,据我了解,在变体一中,不会调用复制构造函数,因此比变体二稍好一些)。
另外,为了进行比较,我做了以下更改。
CASE B
BoundingBox Player::GetBoundingBox(void)
{
return BoundingBox( &GetBoundingSphere() );
}
与变体:
我
BoundingBox& l_Bbox = l_pPlayer->GetBoundingBox();
and II:
BoundingBox l_Bbox = l_pPlayer->GetBoundingBox();
物体l_Bbox
仍然没有走出范围。 “将其绑定到调用函数中的 const 引用,其生存期将扩展到调用函数的范围”,如何真正将对象的生存期扩展到调用函数的范围?
我在这里错过了一些琐碎的事情吗?
通常,临时对象(例如函数调用返回的对象)的生命周期可以延伸到“封闭表达式”的末尾。但是,临时绑定到引用的生命周期通常会“提升”到引用的生命周期(可能是也可能不是调用函数的生命周期),但有一些例外。 12.2/5“临时对象”中的标准涵盖了这一点:
引用所绑定的临时对象或临时对象(临时对象所绑定的子对象的完整对象)在引用的生命周期内持续存在,除非下面指定。构造函数构造函数初始化程序 (12.6.2) 中引用成员的临时绑定将持续存在,直到构造函数退出。函数调用 (5.2.2) 中对引用参数的临时绑定将持续存在,直到包含调用的完整表达式完成为止。
请参阅以下内容了解更多信息:
- C++ 常量引用生命周期(容器适配器) https://stackoverflow.com/questions/2604206/c-constant-reference-lifetime/2604269#2604269
-
GotW #88:“最重要的常量”的候选人 http://herbsutter.com/2008/01/01/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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)