void del函数无法将obj_slot内的类指针设置为NULL;
class test_object {
public:
char *name;
int id;
};
int current_amount;
test_object *obj_slot[512];
void add(test_object *obj)
{
if(current_amount < 512)
{
obj->id = current_amount;
obj_slot[current_amount] = obj;
current_amount ++;
}
else {
std::cout<<"max exceeded";
}
}
void printList(char *status){
printf("%s\n",status);
for(int i = 0 ; i < current_amount ; i ++)
{
printf("list object id %i; string is %s,pointer:%p\n",obj_slot[i]->id,obj_slot[i]->name,obj_slot[i]);
}
}
void del(test_object *obj)
{
printList("before:");
if(!obj)
return;
printf("deleting %s id %i,pointer %p\n",obj->name,obj->id,obj);
for(int i = obj->id ; i < current_amount - 1 ; i ++)
{
obj_slot[i] = obj_slot[i + 1];
}
delete obj;
obj = NULL;
current_amount--;
printList("after:");
}
//这是测试程序:
int main(int argc, char **argv) {
std::cout << "Hello, world!" << std::endl;
for(int i = 0 ; i < 5; i ++)
{
test_object *test = new test_object();
char a[500];
sprintf(a,"random_test_%i",i);
test->name = (char *)malloc(strlen(a) + 1);
strcpy(test->name,a);
add(test);
}
test_object *test = new test_object();
test->name = "random_test";
add(test);
del(test);
printf("test pointer after delete is %p\n",test);
return 0;
}
我已将del函数中要删除的指针地址设置为NULL;但控制台输出仍然是这样的:
之前: list object id 0; string是random_test_0,指针:0x706010
列出对象id 1; string是random_test_1,指针:0x706050
列出对象id 2; string是random_test_2,指针:0x706090
列出对象id 3; string是random_test_3,指针:0x7060d0
列出对象id 4; string是random_test_4,指针:0x706110
列出对象id 5; string是random_test,指针:0x706150
删除random_test id 5,指针0x706150
后: list object id 0; string是random_test_0,指针:0x706010
列出对象id 1; string是random_test_1,指针:0x706050
列出对象id 2; string是random_test_2,指针:0x706090
列出对象id 3; string是random_test_3,指针:0x7060d0
列出对象id 4; string是random_test_4,指针:0x706110
删除后的测试指针是0x706150
*正常退出*
答案 0 :(得分:3)
这是因为在del
函数中,变量obj
是 local 变量,并且对该函数的所有更改都不会在该函数之外可见。如果你想修改它,你应该把它作为参考传递:
void del(test_object *&obj)
{
...
}