|
|
|
|
|
|
|
It is dangerous for one function to create memory and another to free it, however. Ambiguity about who owns the pointer can lead to one of two problems: forgetting to delete a pointer or deleting it twice. Either one can cause serious problems in your program. It is safer to build your functions so that they delete the memory they create. |
|
|
|
|
|
|
|
|
If you write a function that needs to create memory and then pass it back to the calling function, consider changing your interface. Have the calling function allocate the memory and then pass it into your function by reference. This moves all memory management out of your program and back to the function that is prepared to delete it. |
|
|
|
|
| DO | DON'T | | DO pass parameters by value when you must. | DON'T pass by reference if the item referred to might go out of scope. | | DO return by value when you must. | DON'T use references to null objects. |
|
|
|
|
|
|
In this hour, you learned that passing objects by reference can be more efficient than passing by value. Passing by reference also enables the called function to change the value in the arguments back in the calling function. |
|
|
|
|
|
|
|
|
You saw that arguments to functions and values returned from functions can be passed by reference, and that this can be implemented with pointers or with references. |
|
|
|
|
|
|
|
|
You learned how to use const pointers and const references to safely pass values between functions while achieving the efficiency of passing by reference. |
|
|
|
|
|
|
|
|
Q Why have pointers if references are easier? |
|
|
|
|
|
|
|
|
A References cannot be null, and they cannot be reassigned. Pointers offer greater flexibility, but are slightly more difficult to use. |
|
|
|
|
|
|
|
|
Q Why would you ever return by value from a function? |
|
|
|
|
|
|
|
|
A If the object being returned is local, you must return by value or you will be returning a reference to a nonexistent object. |
|
|
|
|
|
|
|
|
Q Given the danger in returning by reference, why not always return by value? |
|
|
|
|
|
|
|
|
A There is far greater efficiency in returning by reference. Memory is saved, and the program runs faster. |
|
|
|
|
|