Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boolean value returned on a function call to null object

Tags:

c++

c++11

What is the boolean value that is returned when a fucntion call is made on a null object in C++?

ClassDummy* dummy = NULL;
if (!dummy->dummy_function(1,2,3)) {
  // Do Something
}

Shouldn't this return an error according to C++11 standards?

like image 603
ibp73 Avatar asked Jun 08 '14 01:06

ibp73


4 Answers

In the original question dummy had an unspecified value, maybe null. The effect after the edit isn't changed, though: The behavior is undefined. Its not an error any tool is required to detect: it is the mandate of the programmer to call member functions only on valid objects.

like image 44
Dietmar Kühl Avatar answered Nov 09 '22 07:11

Dietmar Kühl


Calling a method through a null pointer has undefined behavior. The code is invalid, but the compiler is not required to tell you that it is.

The C++ standard defines many cases where, even though the code is invalid, the compiler is not required to give a "diagnostic". In many cases, the reason is just because it is very difficult for the compiler to determine whether or not the code is valid. In your particular code, this is pretty easy, and some compilers may in fact give a warning about it if you use the proper warning level. However, it wouldn't be too difficult to construct a more complicated example where the compiler wouldn't easily be able to tell whether the pointer was null or not. Standardizing exactly how complex the code has to be before the compiler doesn't need to give a diagnostic would be difficult, and probably pointless, so it is just left up to each implementation to make that decision.

like image 20
Vaughn Cato Avatar answered Nov 09 '22 08:11

Vaughn Cato


Trying to dereference a null pointer like this will result in undefined behavior.

(Typically, a core dump or memory access exception on most systems.)

like image 21
songyuanyao Avatar answered Nov 09 '22 07:11

songyuanyao


Unless dummy has been declared at namespace scope, it is uninitialized and its value is unspecified, i.e. it may or may not be null. Invoking a member function on a nullptr, or on a pointer that is pointing to invalid memory, is undefined behavior.

You might get away with the correct result if the member function you invoke doesn't access any other data members of the class; in other words, if it doesn't dereference the this pointer. However, regardless of whether you obtain the expected result or not, it is still undefined behavior.

Compilers are not required to detect such invalid function calls. If you do something obvious, like initialize an object pointer to nullptr and then invoke a member function on it, you may see a diagnostic from the compiler, but this is not guaranteed.

like image 97
Praetorian Avatar answered Nov 09 '22 09:11

Praetorian