我正在尝试创建一个链接列表,但我在函数内部创建对象并分配指向其地址的指针时遇到问题,因为我认为当函数退出时它们会超出范围。这是真的?并且,如果是这样,我如何在main之外创建一个对象并仍然使用它?

有帮助吗?

解决方案

使用new运算符创建对象。即

void foo( myObject* bar1, myObject* bar2 )
{
  bar1 = new myObject();
  bar2 = new myObject();
  // do something
}

int main( int argc, char* argv[] )
{
  myObject* thing1;
  myObject* thing2;
  foo( thing1, thing2 );

  // Don't forget to release the memory!
  delete thing1;
  delete thing2;

  return 0;
}

其他提示

你是对的,局部变量将超出功能块末尾的范围。您需要创建指向对象的指针,并使用 new 进行分配。当您从列表中删除对象时,不要忘记删除该对象。

如果您不想处理指针附带的麻烦和错误,请参阅 boost :: shared_ptr

使用new运算符:

void f()
{
  CMyObject *p = new CMyObject();
  List.AddTail(p); // Or whatever call adds the opbject to the list
}

当列表被销毁时,请注意删除对象。

为什么不在列表中存储对象(不是指向对象的指针)?创建者函数将返回对象。

如果你真的需要指针列表,可以考虑使用特殊的指针列表容器( boost :: ptr_list )或在其中存储智能指针( boost :: shared_ptr )。为了防止对象在从函数返回后超出范围,您需要使用operator new动态分配它们。

接受的答案是不对的。在函数

void foo( myObject* bar1, myObject* bar2 )
{
  bar1 = new myObject();
  bar2 = new myObject();
  // do something
}

将新分配的对象分配给局部变量。它们不会影响调用函数中指针的值。

int main( int argc, char* argv[] )
{
  myObject* thing1;
  myObject* thing2;
  foo( thing1, thing2 ); // thing1 and thing2 don't get assigned
                         // They continue to be uninitialized in
                         // this function

  // Don't forget to release the memory!
  delete thing1;  // These two deletes will lead to undefined behavior.
  delete thing2;

  return 0;
}

您需要的是:

void foo( myObject*& bar1, myObject*& bar2 )
{
  bar1 = new myObject(); // Now the value of the pointers in the calling
  bar2 = new myObject(); // will be changed since the pointers are passed by reference.
  // do something
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top