在C++中将object数组设置为null

Chi*_*hin 6 c++ arrays null object

假设我在C++中有一个Foo类型的对象数组:

Foo array[10];
Run Code Online (Sandbox Code Playgroud)

在Java中,我可以通过以下方式将此数组中的对象设置为null:

array[0] = null //the first one
Run Code Online (Sandbox Code Playgroud)

我怎么能用C++做到这一点?

Ed *_* S. 7

所以,忘了这里的Java,它没有帮助你.问你自己; 对象为null意味着什么?对象可以为null吗?答案是否定的,一个对象不能为null,而是一个引用(C++术语中的指针)可以.

在java中,您有引用类型,类似于引擎盖下的指针.但是,即使在java中,也不能将对象设置为null,只能引用.

在C++中,您拥有完全成熟的对象和指针以及对象的引用.指向对象(或基本类型)指针可以为null,但对象本身不能.

因此,当您创建一个Foo对象数组时,您就拥有了一个Foo对象数组.你没有指针,你有对象.如果你的数组是一个指向对象的指针数组,那么你可以将它们初始化为null(nullptr在C++ 0x中),即它们不引用有效的对象.


sam*_*hen 6

改为使用指针:

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.
Run Code Online (Sandbox Code Playgroud)

请注意,您需要考虑使用C++进行内存管理,因为与Java不同,它没有垃圾收集器,当您设置对nullptr的引用时,垃圾收集器会自动为您清理内存.此外,nullptr是现代和适当的C++方法,因为而不是总是指针类型而不是零.