Stuart Golodetz wrote:
davee wrote:
Vladimir Jovic wrote:
davee wrote:
I have this function:
void update( MyType * m) {
updateMyType(m);
}
when 'update' returns the caller must see the changes made to m.
But to make this work correctly should 'update' not take a
reference instead:
void update( MyType & m) {
...
When I use the first definition (using a pointer) its not always
that the content of 'm' is correct when 'update' returns. I assume
there is no such thing as a reference to a pointer?
It is not clear what exactly the update() method should do.
Anyway, your assumption is wrong. A reference to a pointer is shown
in this example:
void foo( int *&n )
{
++ *n; // increase value pointed by the pointer
++ n; // advance the pointer
}
Ok so if I do:
void foo( int * n )
{
++ *n; // increase value pointed by the pointer
++ n; // advance the pointer
}
then 'n' will not have a defined value when foo returns?
Not sure what you mean by "have a defined value" here. The pointer
you passed in (i.e. the pointer of which the local pointer n is a
copy) won't be modified. On the other hand, the pointee (the int to
which n points) has been modified, and this will be visible outside
the function by dereferencing the pointer you passed in.
Stu
Lets assume that I have an object 'MyObject' with various fields.
Below foo1 and foo2 modifies the fields in a MyObject object:
void foo1(MyObject * mobj){
int value = 55;
myobj->setValue(value);
...
...
}
void foo2(MyObject *& mobj){
int value = 55;
myobj->setValue(value);
...
...
}
int main(){
MyObject * myobj = new MyObject();
foo1(myobj);
std::cout << "getValue = " << myobj.getValue() << std::endl;
foo2(myobj);
std::cout << "getValue = " << myobj.getValue() << std::endl;
}
As I understand its only when calling foo2 that the changes will
visible in main after returning from the call. The reason is that
foo1 works
on a copy of the pointer which disappears when the function returns.
On contrary foo2 works on the original pointer. Or am I mistaken ?
this copy points to the same object. So, it does not make a difference.
This will also modify the original object.