Antonio Banderas
Antonio Banderas

Reputation: 31

Google test C++ Check if a stream is null

I have a Reference constructor who receive a stream as an argument.

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

I have to check in unit test with Google Test if the stream is non null. I have check on Google what I can do, but I couldn't find anything.

My question is: Do you know how to do it or do you have some tips for me.

Best regards,

Upvotes: 2

Views: 2438

Answers (3)

kiriloff
kiriloff

Reputation: 26333

Maybe you should reconsider why you think you need to test a NULL reference. It is much more likely to mess up with pointers than with references.

For instance, this is giving crash

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

*p = 3;//runtime error

but cannot happen with reference, since reference has to be assigned with its value with value in same scope.

However, there are cases where crash can occur and check would be of use:

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

but then you may want to check the pointer instead, as in

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

So, as said, you are responsible in your code for initialization of references. if your initialization is with the pointee of a pointer, like int& ref(*p);, just check the pointer.

HTH

Upvotes: 0

Rory Chatterton
Rory Chatterton

Reputation: 7

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)

Upvotes: 0

Captain Obvlious
Captain Obvlious

Reputation: 20073

A reference must always be initialized to refer to a valid object or function. A reference not bound to a valid object or function produces undefined behavior. If you need to pass a null value use a pointer, not a reference.

Upvotes: 2

Related Questions