Question

I am trying to create a link list, but I am having trouble creating objects inside a function and assigning pointers to their addresses, since I believe they go out of scope when the function exits. Is this true? And, if so, how can I create an object outside the main and still use it?

Was it helpful?

Solution

Create the objects with the new operator. ie

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

OTHER TIPS

You are correct, local variables will go out of scope at the end of the function block. You need to create pointers to the objects and allocate them with new. And don't forget to delete the object when you remove it from your list.

If you don't want to deal with the hassles and bugs that come with pointers, see boost::shared_ptr instead.

use the new operator:

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

Pay attention to object deletion when your list is destroyed.

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
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top