Another problem with calling by value |

The question is simple and may have been discussed earlier, but I could find a clear answer for my case. Suppose I pass a pointer object to a function

#include "foo.h" int main() { foo * aFoo = new foo; bar(aFoo); delete aFoo; aFoo = NULL; return 0; } 

Then the function is written like this:

 void bar (foo *f) { f->insert(); } 

Question:

Is it a call by value or a call by reference ? I know that in a call by value there is overhead for copying an object from main () to bar (). Therefore, I want to be sure that it is call by reference .

+4
source share
2 answers

This is a call by value, where the value of the aFoo pointer aFoo copied to the function parameter f .

A call by reference is a call where the parameter is a link, and side effects on the argument (and not on the objects pointed to by this argument) that occur inside the function are visible to the caller when the function returns,

So, for example, this is a function that takes a parameter by reference:

 void bar(foo*& f) // ^ // Here you are taking a pointer by reference 

While this is a function that takes a parameter by value:

 void bar(foo* f) // ^ // Here you are taking a pointer to foo by value 

You are probably puzzled by the fact that with foo you can reference and write:

 void bar(foo& f) { f.insert(); } 

has almost the same effect as passing a pointer to the same foo object by value and record:

 void bar(foo* f) { // Precondition: f != nullptr f->insert(); } 

However, two things are conceptually different. Although the value / state of the object that you passed in the first case may differ when the function returns from the value / state that it had before the function call, in the second case, the pointer value you specified will be the same as before how you called bar() - while the object pointed to may undergo some state change.

Also note that the pointer may be null, and the link is always bound to an object.

+11
source

In your case, it is call by value in terms of a pointer to Foo formally. But since you pass a pointer to a function instead of the class instance itself, then it is conceptually called by reference in terms of the class instance, since the function call does not copy the entire instance, but only its pointer.

 Foo fooInstance; // providing a way to point (less formally you can call it refer) to the instance Foo* fooPointer = &fooInstance; // this function call is call by value (passing the value of the pointer). // but you can logically view it as 'call by reference' to fooInstance. bar(fooPointer); 
+1
source

Source: https://habr.com/ru/post/1486078/


All Articles