在C ++中将对象数组设置为null [英] Set array of object to null in C++

查看:344
本文介绍了在C ++中将对象数组设置为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

Foo array[10];

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

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

array[0] = null //the first one

如何在C ++中做到这一点?

How can I do this in C++?

推荐答案

使用指针代替:

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.

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

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.

这篇关于在C ++中将对象数组设置为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆