'reference'에 해당되는 글 1건

  1. 2008.05.02 [C/C++] Using Reference as function parameter...

[C/C++] Using Reference as function parameter...

Language/C&C++ 2008.05.02 23:39
[[ blog 이사 과정에서 정확한 posting날짜가 분실됨. 년도와 분기 정도는 맞지 않을까? ]]

Reference is enhanced concept from Pointer in C++.
So, many C++ books says "Reference is better than Pointer. So try to use Reference if possible."
Yes, reference has several advantages. It guarantees that there is enough memory space for the variable. So, we don't need to do so-called "NULL Check" in most cases (In some evil cases, address can be NULL even if it is reference).
But, in terms of readability, sometimes, using Pointer is better than Reference. Since C, programmers think that parameter is passed by value. Let's see below.

func(a); // --- (*1)
func(&a); // --- (*2)

At first look - before looking at declaration of "func()", programmer tends to think that "Value of 'a' is passed. So, even after (*1), value of 'a' will be preserved." But in case of (*2), they might think that "Address of 'a' is passed. So, after (*2), value of 'a' may be changed."
But, Reference stands against of this 'Popular' concept - reference parameter of 'func()' may change value of 'a'.
But, in case that 'func()' doesn't change 'a', using reference - should be declared as 'const' - as parameter can be good choice.
In other words, if value of parameter is changed, using pointer is better then using reference in terms of readability, in my point of view.

In summary, my recommendation is,

"If possible, use Reference as parameter only when value of parameter is not changed with 'const' keyword."

Trackback 0 : Comment 0

티스토리 툴바