-3

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;但控制台输出仍然是这样的:

之前:列出对象 id 0;字符串是random_test_0,指针:0x706010

列出对象 ID 1;字符串是random_test_1,指针:0x706050

列出对象 ID 2;字符串是random_test_2,指针:0x706090

列出对象 ID 3;字符串是random_test_3,指针:0x7060d0

列出对象 ID 4;字符串是random_test_4,指针:0x706110

列出对象 ID 5;字符串是随机测试,指针:0x706150

删除 random_test id 5,指针 0x706150

之后:列出对象 id 0;字符串是random_test_0,指针:0x706010

列出对象 ID 1;字符串是random_test_1,指针:0x706050

列出对象 ID 2;字符串是random_test_2,指针:0x706090

列出对象 ID 3;字符串是random_test_3,指针:0x7060d0

列出对象 ID 4;字符串是random_test_4,指针:0x706110

删除后的测试指针为0x706150

* 正常退出 *

4

1 回答 1

3

这是因为在del函数中,变量obj局部变量,对它的所有更改在该函数之外都是不可见的。如果要修改它,则应将其作为参考传递:

void del(test_object *&obj)
{
    ...
}
于 2012-11-04T12:10:38.280 回答