Re: newbie on pointers
"Henrietta Denoue" <henrietta@netcalcul.fr> wrote in message
news:euora1$2sdm$1@news01.tp.hist.no...
Hi,
What happens to a global pointer that is to be used in various
other objects, is instantiated in one object, then this second
object is deleted ? Is the pointer still valid ? like pseudo-code
---------------------------
// my global pointer, not a member of Classes A or B
X *x;
class A{
....
x = new X();
... do something with x
As long as that something doesn't include delete x
}
Class B {
...
do something with x;
}
int main()
{
A a;
B b;
a = new A();
....
delete a;
---------------
My question is : Is x still valid in B evenif A is deleted ?
When you call new you are returned a memory address where that instance
resides. Having that pointer and what type it is is all you need to get
access to the object, until it is deleted. It doesn't matter where new is
called, as long as you have the address.
So the answer to your question is: yes, b (not B) is still valid after a
(not A) is deleted, as long as a never deleted the pointer itself. As long
as a didn't delete the pointer in it's destructor or other methods.
Now, the use of globals is a bad thing, because it causes confusion as to
when something is created/deleted without looking at the classes themselves.
If you need a class to create a new object (such as a factory class) then
the method that creates the object should return the pointer, which you
would store. Modifying your code a little bit (may contain errors, not
tested):
class A
{
public:
X* Factory() const { return new X(); }
};
class B
{
// Class B needs to get the pointer. A few ways to get it.
// If the created object is going to live for the lifetime of
// the program, it could be passed in the constructor and
// copied. If it's just going to be used by a method, then
// it should be passed as a parm. I'll attempt to show
// both ways.
public:
B( X* x ): Xp( x ) {}
void Foo() { // We can use Xp here which was copied in the construtor }
void Bar( X* x ) { // We can use x here, which was passed as a parm }
private:
X* Xp;
};
int main()
{
A a;
X* MyX = a.Factory();
B b( MyX );
b.Foo(); // Uses pointer passed in constructor
b.Bar( MyX ); // Uses pointer we just passed
delete MyX; // Important to only do this once
};
As you can see, all we need is to get a copy of the ponter and use it
somewhere. It remains valid until delete is called, even if whatever
created it goes out of scope or is deleted itself, as long as delete is not
called on that specific pointer somewhere.