代码之家  ›  专栏  ›  技术社区  ›  JosanSun

为什么我们需要检查C++中的空指针,而不是在Java中呢?

  •  -8
  • JosanSun  · 技术社区  · 6 年前

    如果是这样的话,我有一个类,名为 RequestType . 在爪哇,代码倾向于不检查任何新对象是否为空引用:

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

    但是C++代码倾向于检查分配:

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

    为什么我们需要检查RequestType是否是 nullptr 在C++中,但是在Java中没有这样的检查就可以使用它吗?

    2 回复  |  直到 6 年前
        1
  •  1
  •   Toby Speight    6 年前

    你的前提是错误的(可能是由普通的样品通知)。

    在两种语言中, new 运算符将成功或引发异常( java.​lang.​OutOfMemoryError std::​bad_alloc ,分别)。所以不需要检查这样一个新分配的对象。(注意这里我说的是标准C++——一些古老的标准编译器会返回NULL而不是抛出)。

    当一个函数在它的控制之外接收一个参数时,一个防御性的程序员通常会检查Java引用和C++指针,这两个指针都可以是空的。对C++引用如此保守是不常见的,因为隐式契约是我们不在C++中创建空引用。


    总结

    • 在Java中新分配的对象永远不能为空:

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

      也不在C++中:

      Request* request = new Request();
      // request cannot be null
      
    • Java中的函数参数或返回值可能为空:

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

      在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)
      
        2
  •  -3
  •   Incredible    6 年前

    在爪哇中,下面的语句显式创建对象,并且将永远不会创建 null 直到或除非它是默认构造函数。

    RequestType requestType = new RequestType();
    

    但是,如果您将此对象作为方法参数接收,或者在 return 语句或构造函数在创建此对象时正在执行某些逻辑,因此有可能 无效的 .

    因此,在Java中,还需要检查对象是否是 无效的 或者没有。