Re: delete
On Jun 27, 9:23 am, Erik Wikstr=F6m <Erik-wikst...@telia.com> wrote:
On 2007-06-27 07:46, Senthil wrote:
On Jun 27, 9:34 am, Nethali <neth...@gmail.com> wrote:
Please explain me the following:
I have struct as follows:
struct Link
{
void* data;
Link* next;
}
And I do following:
Link* newLink = new Link;
newLink->data = new string("aaaaaaaaaaaa");
newLink->next = 0;
My problem is this:
Above, I have allocated 2 memory areas, one for newLink and one for
string of "aaaaaaaaaaaa".
If I delete newLink ( ie: delete newLink; ) it will release the memory
area for newLink.
Yes,delete newLink would release the memory area for newLink object.
Will it release the memory area allocated for
"aaaaaaaaaaaa" also? If so how it happens? If it is not so, how can I
relase memory area allocated for "aaaaaaaaaaaa"?
No it does not release the memory for the string that you allocated
using new, it has to be deleted explicitly.
so your clean up code should be something like
delete static_cast<string*>(newLink->data);
delete newLink;
You can make it automatic by using a destructor:
struct Link {
void* data;
Link* next;
~Link();
};
Link::~Link() {
delete static_cast<string*>(this->data);
}
Now the data will automatically be freed when the Link is. Of
course if you're always gonna store strings make data a
string* from the start, then you don't have to cast and the
code will be better.
I think the key to the problem is there. If Link knows it will
be storing strings, then:
struct Link
{
std::string data ;
Link* next ;
} ;
is by far the best solution. And if Link doesn't know the type
of it's data, it can't delete it.
In C++, there are really only two acceptable solutions. If all
of the links have the same type of data:
template< typename T >
struct Link
{
T data ;
Link* next ;
} ;
Otherwise, something like:
struct AbstractData
{
virtual ~AbstractData() {}
} ;
template< typename T >
struct Data : public AbstractData
{
T value ;
} ;
struct Link
{
AbstractData* data ;
Link* next ;
explicit Link( AbstractData* init = NULL )
: data( init )
, next( NULL )
{
}
~Link() { delete data ; }
} ;
(I would not provide the destructor without also providing a
constructor to ensure that it could be called without undefined
behavior.)
Or use something existing, like boost::any, which more or less
wraps the data, takes care of all of the bookkeeping for you,
and provides a lot of support functions. (Somewhere deep inside
of boost::any, I'll bet you'll find something like the
AbstractData/Data pair above.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34