C++ Reference Variable

1480 단어 CC

Characteristic of "Reference Variable"

1) Have to be Initialized

int lvalue = 3;
int &ref ; // error

2) Have to be Initialized with 'l-value'

"l-value" vs "r-value"

l-value : value that has an memory assigned by OS
r-value : x ex) literal, number

int l_value = 3; // l_value having value '3' with memory assigned by OS
int &ref = l_value; // ok
int &ref = 3; // no

3) Value, Address All same with " original variable"

int l_value = 3;
int &ref = l_value;

cout << ref << l_value << endl;   // same
cout << &ref << &l_value << endl; // same

4) no need to "copy" variable when used as function parameter

  • Much more Effective In terms of Processing
int main()
{
	int l_value = 3;
    doSth(l_value)
}

// - variable 'l_value' itself is inserted as parameter
// - with no 'variable copying' process 
void doSth(int &l_value)
{
	cout << "ref" << ref << endl;
}

// - variable 'l_value' is copied
// address of 'l_value' in 'main' &&
// address of 'l_value' in 'doSth'
// is different , since new variable 'l_value' is generated as a result of 'copy'
void doSth(int l_value)
{
	cout << "ref" << ref << endl;
}

좋은 웹페이지 즐겨찾기