๐ ์ฌ๋ฌ ์๋ฃ๋ค์ ํ์ํ๊ณ , ๊ฐ์ธ ํ์ต ์ฉ๋๋ก ์ ๋ฆฌํ ํฌ์คํธ์ ๋๋ค.
์๋ชป๋ ์ ์ด ์๋ค๋ฉด ํผ๋๋ฐฑ ํด์ฃผ์๋ฉด ๊ฐ์ฌํ๊ฒ ์ต๋๋ค!

๋ณต์ฌ ๊ฐ ์์ต๋๋ค.์ฐธ์กฐ์ ๋ณํ๋ ๊ฐ์ฒด ๋ฐ์ดํฐ์ ๋ณํ๋ caller scope์ ๋ฐ์๋ ๊ฒ์
๋๋ค. & ๋ฅผ ์ฌ์ฉํ์ฌ pass by reference๋ฅผ ํ์ฉํ๋ค.๋์ผํ ๋ณ์์ด๋ค.
๋ณต์ฌํ๋ ๊ฒ์ ์๋ฏธํ๋ค.call by value์ ๋์์ด์์ผ์ ๋ฐ๋ผ ๋ค๋ฅด๊ฒ ๋ถ๋ฆฌ๋ ๊ฒ ๊ฐ๋ค.์ฐธ์กฐ ๋ผ๋ ์ฉ์ด๋ ๊ฐ๋ณ์ ์ธ ์๋ฏธ๋ก ์ค๋ฒ๋ก๋ ๋ ๊ฒ์ด๋ค.
Java์์ Reference ๋ ๋จ์ํ ํฌ์ธํฐ๋ฅผ ์๋ฏธ
ํฌ์ธํฐ ๋ฅผ ์ฐธ์กฐ ๋ก ํธ์ถํ๋ค๋ ์ ์ ์ ์ธํ๊ณ ๋ ํฌ์ธํฐ๋ฅผ ๋ฉ์๋์ ์ ๋ฌํ๋ค๋ ์ ์ ์ฐจ์ฉํ๋ค๊ณ ํ๋ค.Java์ ์ฐธ์กฐํ์
(Reference Type)
- ๊ฐ์ฒด์ ์ฃผ์๋ฅผ ์ฐธ์กฐํ๋ ํ์
์ผ๋ก ๋ฐฐ์ด, ์ด๊ฑฐ, ํด๋์ค, ์ธํฐํ์ด์ค ํ์
C++์ ์ฐธ์กฐ๋ณ์(&)
Pass-by-reference ์ ๋งฅ๋ฝ์์๋ ์ค๋ฆฌ์ง๋ ๋ณ์์ ํธ๋ค๋ง์ ์๋ฏธ
์ด๋ฌํ ์ฉ์ด์ ํผ๋์ผ๋ก call by sharing ์ด๋ผ๋ ์ฉ์ด๊ฐ ์๊ธฐ๊ธฐ๋ ํจ.
call by value์ call by reference ์ ๊ฐ๊ฐ ํน์ง์ด ์์ฌ์๋ ๊ฒ์ ๋งํ๋ ๊ฒ ๊ฐ๋ค.๊ณต์ ํด์ ์๋ณต ๊ฐ์ฒด์ ์ํ ๋ณ๊ฒฝ ๊ฐ๋ฅํ๋ค.์๋ฐ๋ argument๋ก reference type์ ๋ณด๋ผ ์ ์๋๋ฐ?์์ ์์๋ ํผ๋ ๊ฐ๋ค.
์ ๋ฌ๋ ๊ฐ์ฒด์ ์ํ๋ฅผ ๋ณ๊ฒฝ์ํฌ ์ ์๊ธฐ ๋๋ฌธ์ด๋ค.
ํ์ง๋ง, ์๋ ๊ทธ๋ฆผ๊ณผ ๊ฐ์ด ์ฐธ์กฐ๋ณ์ a๊ฐ ๊ฐ๋ฆฌํค๋ ์ธ์คํด์ค์ ์ฃผ์๊ฐ์ ๋ณต์ฌ ํ์ฌ,
๋์ผํ ์ธ์คํด์ค๋ฅผ ๊ฐ๋ฆฌํค๊ณ ์๋ ์ฐธ์กฐ๋ณ์ b ๋ผ๋ ๊ณต๊ฐ์ด ์ถ๊ฐ๋ก ์์ฑ๋ ๊ฒ์ด๋ค.

๋ฐ๋ผ์, ์ฐธ์กฐ๋ณ์๊ฐ ๊ฐ๋ฆฌํค๋ ๊ฐ์ฒด์ ์ํ๋ฅผ ๋ณ๊ฒฝ์ ํ๋ ๊ฒ์ ๊ฐ๋ฅํ๋ค.
ํ์ง๋ง ์ฐธ์กฐ๋ณ์ b ์ ์ฐธ์กฐ๋ณ์ a๋ ๊ด๊ณ๊ฐ ์๋ ๊ฐ๋ณ์ ์ธ ์์์ด๋ค.
์ฆ, ์ ๋ฌ๋ ์ฐธ์กฐ๋ณ์ a ์์ฒด๋ฅผ ๋ณ๊ฒฝํ ์๋ ์๋ค.
ํผ๋์ด๋ค.
Pyro๋ ์๋ฃ ์คํฌ๋จ
์๋ฐ์์ pass by value ๋ง์ ํ์ฉํ๊ณ ,
call by reference ๋ฅผ ํ์ฉํ์ง ์๊ฒ ๋ค๋ ์๋ฆฌ๋,
function call ๋ก ์ธํside effect๋ฅผ ํ์ฉํ์ง ์๊ฒ ๋ค๋ ์ธ์ด ์ค๊ณ ์ฒ ํ์ ์ด์ผ๊ธฐํ ๊ฒ์ด๋ค.
๊ทธ๋ฅ swap ์ด ๋ถ๊ฐ๋ฅํ๋ฉด ์ ๋ถ call by value ๋ผ๊ณ ์๊ฐ์ ํ์.
C++ ์์
#include <iostream>
using namespace std;
void foo(int &x) { //์ฐธ์กฐ ์ฐ์ฐ์
x *= 10;
}
void bar(int *x) {
*x *= 10;
}
int main(int argc, char const *argv[])
{
int x = 10;
int y = 10;
foo(x); //call by reference
bar(&y); //call by addresss
cout << x << endl;
cout << y << endl;
return 0;
}
output
> 100
> 100
Java ํ๊ฐ๋ฆฌ๋ ์์
class Company{
private String name;
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
}
public class copyEx2{
public static void main(String[] args){
Company com1 = new Company();
com1.setName("Google");
show(com1);
System.out.println("main(): "+com1.getName());
}
public static void show(Company com){
com = new Comapny(); // ๐ ์ฃผ๋ชฉ!
com.setName("Yahoo");
System.out.println("show(): "+com.getName());
}
}
output
> show():yahoo
> main():Google
์ฐ์๐๐ ๊ทธ๋ฆผ์ด ์์ผ๋๊น ํจ์ฌ ์ดํด๊ฐ ์ ๋๋ค์๐ฏ๐ฏ