Link to home
Start Free TrialLog in
Avatar of jhapak
jhapak

asked on

MFC, Pointers and References

Hello,
Suppose I have two pointers in two different functions and I have a public variable, lets say:
sh1(){
Shape *sh1 = new Shape;
global_sh = sh1;
}

sh2(){
Shape *sh2 = new Shape;
global_sh = sh2;
}

What I want is something to store the address of the point sh1 or sh2 in global_sh. Now somewhere else I declare another pointer "sh3" and say sh3 = global_sh. Now if I say sh3.something() then it should return/call the related object. How can i do it?

Saqib
Avatar of Skonen
Skonen

Shape *global_sh;

// ....

sh1(){
Shape *sh1 = new Shape;
global_sh = &sh1;
}

sh2() {
Shape *sh2 = new Shape;
global_sh = &sh2;
}

// ...

Shape *sh3;

sh1();
sh3 = global_sh;
sh3->Something();
Skongen:

> Shape *sh1 = new Shape;
> global_sh = &sh1;

that's bad, since you take the address of a temporary object. looking at the calling code you probably meant

global_sh = sh1;

Saquib:
With above correction, this would work fine.
However, you have another problem: who is going to delete the shapes?

If you call

sh1();
sh2();

at least the first allocation leaks, because it is not accessible anymore.
To solve that, I'd recommmend using reference counted pointers (e.g. boost::shared_ptr)
Sorry about that, looking back at that I see no reasoning in what I did. I assumed he was going to delete global_sh afterwards so I didn't mention anything about freeing the allocated memory once he was done.
Avatar of jhapak

ASKER

ok,
I have checked smart pointers, cool thing.

But, my problem is that am using CObList and I have different classes in it. So when ever I put an object on the list it gives me memory leak. Any idea?? How can I delete manually a pointer then?
ASKER CERTIFIED SOLUTION
Avatar of peterchen092700
peterchen092700

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial