【发布时间】:2011-04-15 15:08:05
【问题描述】:
我注意到当我不小心忘记从应该返回引用的函数返回时,我没有收到任何编译器错误。我写了一些小测试来看看实际发生了什么,我比什么都更困惑。
struct Foo
{
int x;
Foo() {
x = 3;
}
};
Foo* foo = new Foo;
Foo& test(bool flag) {
if (flag)
return *foo;
}
如果 test() 没有(明确地)返回值,我仍然会返回一些东西。然而,返回的 Foo 对象并未使用默认构造函数进行初始化——这是因为 x 在非显式返回值中与 3 不同。
当您不返回引用时实际发生了什么?如果这是一项功能,那么将其用作在发生错误时返回虚拟对象的方法是否安全,而不是返回空指针。 (请参见下面的示例。)
class FooFactory
{
// Return reference...
Foo& createFooRef() {
Foo* foo = new Foo;
bool success = foo->load();
if (success)
return *foo;
// Implicit (and safe?) return value on failure?
}
// ... as opposed to returning a pointer.
Foo* createFooPtr() {
Foo* foo = new foo;
bool success = foo->load();
if (success)
return foo;
else
return 0;
}
// Yes, I am aware of the memory leaks,
// but that's not the point of the example.
【问题讨论】:
-
Microsoft 的 VC(Visual Studio 2010 Express 附带的那个,如果有影响的话)。
标签: c++ function reference return-value