How to convert a local variable to a pointer in C ++?

I have a variable that is an object:

Foo x;

And I need to call a function that requires Foo *. How can I convert from Foo to Foo *.

I know this work does not work:

Foo* y = &x;
o->setFoo(y);

Because "x" is a local variable, so it will be destroyed, and the pointer I gave will not indicate anything.

How can i do this?

Note: I cannot change the function or variable type a!

+5
source share
4 answers

If the appropriate copy constructor is specified,

o->setFoo(new Foo(x));

But then the destructor oshould delete x(and setFoopossibly also if it is already installed. \ S is already installed).

. .
- /:

  • .
  • , ,
  • , .

4.

o, / , .

+6

new:

Foo* y = new Foo;
o->setFoo(y);

Foo , .

+2

, , o Foo, o.

-, , , o Foo.

, :

Foo* y = &x;
o->setFoo(y);

"x" - , , , , .

, , o Bar

1 Bar Foo - .. Foo.

, - , Foo , Foo ,

{
 std::auto_ptr<Bar> o = new Bar();
 o->setFoo(new Foo());
 o->DoStuff();
}

{
 std::auto_ptr<Foo> y = new Foo(...);
 y->config();
 o->setFoo(y.release());
}

2 Foo - .. Foo

Bar Foo, , , Bar Foo

2.1 , Bar
Bar Foo

{
 Foo y;
 std::auto_ptr<Bar> o = new Bar();
 o->setFoo(&y);
 o->DoStuff();
}

2.2 , Bar

SomeFunc( Foo *y );
{
 std::auto_ptr<Bar> o = new Bar();
 o->setFoo(y);
 o->DoStuff();
}

{
 Foo y;
 SomeFunc( &y );
}

2.3 suggests that you have a panel that will be used in different areas

std::auto_ptr<Foo> y = new Foo();
std::auto_ptr<Bar> o = new Bar();

{
 o->setFoo(y.get());
}
{
 o->DoStuff();
}

and then you can give other examples based on how you work with Foo for several bars, including containers, etc.

+2
source

You can dynamically highlight a class object Foousing a new one, for example

o->setFoo(new Foo);

Please note that you must consider the ownership of this object, because if it setFoodoes not delete it, you will have a memory leak.

+1
source

All Articles