2

我有一个参考构造函数,它接收一个流作为参数。

Reference::Reference(std::istream& p_is)
{}

如果流不为空,我必须使用 Google Test 签入单元测试。我在谷歌上检查了我能做什么,但我找不到任何东西。

我的问题是:你知道怎么做吗,或者你有什么建议给我。

此致,

4

3 回答 3

2

必须始终初始化引用以引用有效的对象或函数。未绑定到有效对象或函数的引用会产生未定义的行为。如果您需要传递空值,请使用指针,而不是引用。

于 2013-04-10T03:44:57.543 回答
0

As Captain Obvlious pointed out, you can't have a reference to an invalid object/function. You could either pass it as a pointer, or only call to the constructor if(!p_is.good()) if you aren't restricted by the use of Google Test (Sorry, I'm not familiar with Google Test's functionality, so I might just be re-iterating what has already been said)

于 2013-04-10T04:47:42.260 回答
0

也许您应该重新考虑为什么您认为需要测试 NULL 引用。与引用相比,指针更容易搞砸。

例如,这会导致崩溃

int *p;
if(true)
{
  int x;
  p = &x;
}

*p = 3;//runtime error

但不会发生在引用中,因为必须为引用分配它的值,并且值在同一范围内。

但是,在某些情况下可能会发生崩溃并且检查会很有用:

 int* p = 0;
 int& ref(*p);
 int i(ref);  // access violation here

但随后您可能想要检查指针,如

int* p =0;
if (p)
{
  int& ref(*p);
  int i(ref);
}

因此,如前所述,您负责在代码中初始化引用。如果您的初始化是使用指针的指针,例如int& ref(*p);,只需检查指针。

高温高压

于 2013-04-27T19:54:20.217 回答