Set array of object to null in C++

前端 未结 4 1481
深忆病人
深忆病人 2021-02-06 04:46

Suppose I have an array of objects of type Foo in C++:

Foo array[10];

In Java, I can set an object in this array to null simply by:

<         


        
4条回答
  •  眼角桃花
    2021-02-06 05:19

    So, forget Java here, it's not helping you. Ask yourself; what does it mean for an object to be null? Can an object be null? The answer is no, an object can not be null, but a reference (pointer in C++ terms) to one can be.

    In java you have reference types, which are similar to pointers under the hood. However, you cannot set objects to null even in java, only references.

    In C++ you have fully fledged objects and pointers and references to objects. A pointer to an object (or primitive type) can be null, but an object itself cannot.

    So, when you create an array of Foo objects you have, well, an array of Foo objects. You don't have pointers, you have objects. If your array were an array of pointers to objects then yes, you could initialize them to null (nullptr in C++0x), i.e., they don't refer to a valid object.

提交回复
热议问题