Click to See Complete Forum and Search --> : delete const object


blopez
May 27th, 2002, 03:55 AM
class A {
public :
A();
~A();
int f();
};

class B {
public :
A* a;

B();
~B();
const A* getA();
};

void main(void) {
B b ;
const A* a = b.getA() ;
delete a;
}

I have found a solution, using a third class C, having the same interface of A and a menber A*. The destructor of this class doesn’t delete the pointer and I have changed the class B which return an pointer on a class C.
I just want to know if there is an other solutions.

Bruno.

AlanGRutter
May 27th, 2002, 04:09 AM
Err, I have to ask - what are you doing ??


In class B, member a is in the public interface, so getA() isn't required anyway.
a is never assigned to, and if it was then class B also needs a proper copy constructor and operator= function. Otherwise you will get exceptions and memory leaks.
a is owned by objects of type B. Deleting a outside of this context will surely lead to disaster.


Any object of type B owns the pointer, hence that object should be responsible for deleting it. If you want to change/delete it then write proper member functions in B to free the old memory first.

Regards
Alan

blopez
May 27th, 2002, 04:19 AM
Excuse me. Of course, a is not a public member of b.
At first time, the function getA of the class B return a copy of a. But, in my context, I don't want to make a copy of the memory, so I return a const pointer to the instance of a.

For the 3), I know that, it's why I ask the question. My solution is :

class A {
public :
A();
~A();
int f();
};

class B {
A* a;

public :
B();
~B();
const C* getC();
};



class C {
A* a;
public :
C();
~C();
int f();
};

with int C::f() {
if(a);
return a->f();
else
return -1;
}

blopez
May 27th, 2002, 04:22 AM
oups:

class B {
C* c;

public :
B();
~B();
const C* getC();
};


Excuse me...


:)

AlanGRutter
May 27th, 2002, 04:30 AM
Since you say that you do not want a copy of the memory then your original version of getA() will suffice. It is only returning a pointer - this pointer points to the same as a.

Incidentally, const A* means that the data is constant not the pointer, which can be moved.

Since your pointer is only a copy of a pointer and not the memory, then only this pointer is destroyed when it goes out of scope, not what's being pointed to. Only B can destroy that.

You don't need to do a delete of this specifically because it wasn't created using new.

Regards
Alan