Set array of object to null in C++

前端 未结 4 1332
深忆病人
深忆病人 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:15

    Use pointers instead:

    Foo *array[10];
    
    // Dynamically allocate the memory for the element in `array[0]`
    array[0] = new Foo();
    array[1] = new Foo();
    
    ...
    
    // Make sure you free the memory before setting 
    // the array element to point to null
    delete array[1]; 
    delete array[0]; 
    
    // Set the pointer in `array[0]` to point to nullptr
    array[1] = nullptr;
    array[0] = nullptr;
    
    // Note the above frees the memory allocated for the first element then
    // sets its pointer to nullptr. You'll have to do this for the rest of the array
    // if you want to set the entire array to nullptr.
    

    Note that you need to consider memory management in C++ because unlike Java, it does not have a Garbage Collector that will automatically clean up memory for you when you set a reference to nullptr. Also, nullptr is the modern and proper C++ way to do it, as rather than always is a pointer type rather than just zero.

提交回复
热议问题