Can reference guarantee non-empty input?
Previously, when discussing the difference between pointer and reference, one may say that the argument passed as reference can guarantee non-empty input. We may just simply take it for granted, but it does not hold for all cases.
For instance,
What happens for the above code? The "input" is a null-reference.
After reading c++ standard, it can be found that dereferencing a null pointer has undefined behavior, so, the above code has broken c++ standard already and is not suggested to use.
"[Note: in particular, a null reference cannot exist in a well-defined program, because the only way to create such a reference would be to bind it to the "object" obtained by dereferencing a null pointer, which causes undefined behavior]"
For instance,
1: class TempClass
2: {3: public:
4: int member;
5: }; 6: 7: void TestFunction(TempClass& input)
8: { 9: TempClass* pInput = &input;10: if(pInput == NULL)
11: throw;
12: int value = input.member;
13: } 14: 15: TempClass* p = NULL; 16: TestFunction(*p); 17: After reading c++ standard, it can be found that dereferencing a null pointer has undefined behavior, so, the above code has broken c++ standard already and is not suggested to use.
"[Note: in particular, a null reference cannot exist in a well-defined program, because the only way to create such a reference would be to bind it to the "object" obtained by dereferencing a null pointer, which causes undefined behavior]"
Comments
Post a Comment