"Thomas" <
XXXX@XXXXX.COM >wrote in message
Quote
If I am passing a pointer (or array of pointers) to a function, Which
pointers do I need to deallocate after use?
Can you rephrase your question? It's not clear what you mean since I can
pass pointer just for fun of it and no deallocation needed:
char *Increase( char *_pcDummy )
{
return( _pcDummy + 1 );
}
On the other hand, I can pass pointer to free and it will deallocate memory
allocated with another function malloc.
Quote
I understand currently that if I create the pointer in one unit then I
deallocate it in the same unit (or function), but what
about when this pointer is passed on to a function(in another unit) as a
parameter. Since there is no allocation of the pointer in that function
there is no need for deallocation in that function either (??)
By "unit" you mean a compilation module, i.e. .cpp file? Or a code module,
i.e. DLL/EXE?
You can allocate and free memory in different modules in both cases though.
with some care if you do it accross DLL/EXE module boundaries.
Quote
Does it make a difference if I pass the pointer by value or by reference
when it comes to deallocating the pointer?
It does not matter, but why would you do this? Pointer takes 4 bytes and
reference is essentually is a pointer to an object, so it takes 4 bytes as
well. In your case using reference to a pointer you'll pay the price of...
hmm... someone correct me if I'm wrong... One LEA at function call and one
MOV per use of reference.
Using references makes sense when you want function to look and behave like
if it takes an object while saving time for creating a temp object at
function call (when object is big, say, some class ):.
Consider:
class CBar
{
public :
unsigned int uiPar[ 8192 ];
};
void Foo1( CBar _clDummy )//by value
{
unsigned int a = _clDummy.uiPar[ 7 ];
}
void Foo2( CBar &_rclDummy )// by reference
{
unsigned int a = _rclDummy.uiPar[ 7 ];
}
CBar bar;
Foo1( bar );
Foo2( bar );
Calls look the same, but for Foo1 compiler will actually create copy of
_clDummy (which is 8193 bytes ) on Foo1's stack. For Foo2 it will create a
reference on stack ( reference is 4 bytes ). Basically, never pass anything
that is not a pre-defined type by value. Use either pointer( clearer and
better way, my opinion) or reference. Another thing with references is that
if formal types of argument and reference do not match but can be converted
one to another, compiler will create temp object of needed type, initialize
it with given object, initialize reference with temp object, pass reference
to the function and then delete temp object at function exit. It does so
quetly, so sometimes it's hard to catch and those temp object can be big. So
my advice, use pointers.
Azazello.