Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

pointers

I have a variable that is an object :

Foo x;

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

I know this wont work :

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

Because "x" is a local variable, so it will be destroyed and the pointer I gave will point to nothing.

How can I do ?

Note : I can't modify the function or the type of the variable a !

like image 727
Matthieu Napoli Avatar asked Nov 01 '10 18:11

Matthieu Napoli


2 Answers

If the appropriate copy constructor is defined,

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

But then o's destructor should delete x (and setFoo probably should too if it'.\s already set).

Note: defining a destructor is not enough.
The copy constructor/assignment operator also need to be defined and:

  • Should be disabled
  • or Understand what they point at and perform a deep copys
  • or understand shared ownership and track how many owners the pointer has.

See Rule of 4 for explanation.

If you can't touch the class definition of o at all, then you'll need to be very careful about the memory allocation/deallocation so you don't leak memory.

like image 135
user470379 Avatar answered Oct 15 '22 11:10

user470379


You should allocate on the heap with the new keyword:

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

though you will need to manage the deletion of the Foo later on, otherwise you get memory leak.

like image 40
Lie Ryan Avatar answered Oct 15 '22 11:10

Lie Ryan