Skip to content
Advertisement

Why do we need to check null pointer in C++, but not in Java?

Supposed that, I have a class named of RequestType. In Java, code tends not to have any check for a new object being a null reference:

RequestType request = new RequestType();
// if (request == null)   // missing

But C++ code tends to check the allocation:

RequestType* request = new RequestType();
if (nullptr == request)      // check

Why do we need to check whether requestType is nullptr in C++, but can just use it without such a check in Java?

Advertisement

Answer

Your premise is mistaken (perhaps informed by mediocre samples).

In both languages, the new operator will either succeed or throw an exception (java.​lang.​OutOfMemoryError or std::​bad_alloc, respectively). So there’s never a need to check a newly-allocated object like that. (Note here that I’m talking about Standard C++ – some ancient pre-Standard compilers would return null instead of throwing).

When a function receives an argument outside of its control, a defensive programmer will normally check Java references and C++ pointers, both of which can be null. It’s less common to be so defensive with C++ references, as the implicit contract is that we don’t create null references in C++.


Summary

  • A newly allocated object can never be null in Java:

    Request request = new Request();
    // request cannot be null
    

    Nor in C++:

    Request* request = new Request();
    // request cannot be null
    
  • A function argument or return value might be null in Java:

    void processRequest(Request request) {
         // request might be null
         String body = request.body();
         // body might be null
    

    And in C++:

    void processRequest(const Request *request) {
         // request might be null
         const char *body = request->body();
         // body might be null
    
    void processRequest(const Request& request) {
         // &request assumed non-null
         std::string body = request.body();
         // body can't be null (it's not a pointer)
    
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement