문제

링크 목록을 만들려고 노력하고 있지만 함수 내부에서 개체를 만들고 주소에 포인터를 할당하는 데 어려움이 있습니다. 이것이 사실입니까? 그렇다면 메인 외부의 객체를 어떻게 만들고 여전히 사용하려면 어떻게해야합니까?

도움이 되었습니까?

해결책

새 연산자로 객체를 만듭니다. 즉

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;
}

다른 팁

당신이 맞습니다. 로컬 변수는 함수 블록의 끝에서 범위를 벗어납니다. 객체에 포인터를 만들고 다음과 함께 할당해야합니다. 새로운. 목록에서 객체를 제거 할 때 객체를 삭제하는 것을 잊지 마십시오.

포인터와 함께 제공되는 번거 로움과 버그를 다루고 싶지 않다면 참조하십시오. 부스트 :: shared_ptr 대신에.

새 연산자 사용 :

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

목록이 파괴 될 때 객체 삭제에주의하십시오.

Why don't you store objects (not pointers to objects) in list? Creator-function will return object.

If you really need list of pointers consider using special pointer list containers (boost::ptr_list) or storing smart pointers in it (boost::shared_ptr). To prevent objects going out of scope after returning from function, you need to dynamically allocate them with operator new.

The accepted answer is not right. In the function

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

the newly allocated object are assigned to local variables. They don't affect the values of the pointers in the calling function.

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;
}

What you need is:

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