그럴듯한 개발 블로그
Published 2023. 7. 6. 18:56
c++ 레퍼런스(참조자) <language>/c++
반응형
// 포인터와 레퍼런스의 차이를 알아보는 코드이다.
int	main() {
	std::string	str = "HI THIS IS BRAIN";
	std::string	*stringPTR;
	std::string	&stringREF = str; // 레퍼런스는 선언하면서 초기화 해줘야 한다.
	stringPTR = &str;
 // 주소 출력부
	std::cout << &str << std::endl;
	std::cout << stringPTR << std::endl;
	std::cout << &stringREF << std::endl;
    // 전부 같은 str의 주소를 찍고있다.
// 들어있는 값 출력부
	std::cout << std::endl;

	std::cout << str << std::endl;
	std::cout << *stringPTR << std::endl;
	std::cout << stringREF << std::endl;
    //전부 str에 담긴 값을 찍고 있다.
}
  • 레퍼런스가 포인터 보다 좋은 점
    • 함수 인자로 받았을 시 포인터와 달리 *, &를 붙히지 않아도 되서 코드가 깔끔해진다.
    • 데이터의 주소를 저장 해야 할 때가 아니면 저장 하지 않아 메모리를 아낄 수 있다.
    • Null 포인터 예외를 방지: 레퍼런스는 반드시 초기화해야 하며, 초기화되지 않은 레퍼런스를 사용하려고 하면 컴파일 에러가 발생한다. 이는 런타임 시점에서 발생할 수 있는 null 포인터 예외를 사전에 방지하여 안정성을 높인다.
class Weapon {
	private:
		std::string	_name;
	public:
		Weapon(std::string name);
	void		setType(std::string name);
	const std::string	&getType(void);
};

class HumanA
{
	private:
		std::string	_humanName;
		Weapon	&_weaponName; // 레퍼런스라 무조건 무기가 장착되어 있다.
	public:
		HumanA(std::string name, Weapon &weaponName);
		void		setHumanName(std::string name);
		std::string	getHumanName(void);
		std::string	getWeaponName(void);
		void		attack();
};

class HumanB
{
	private:
		std::string	_humanName;
		Weapon	*_weaponName; // 포인터라 무기를 들고 있지 않을 수 있다.
	public:
		HumanB(std::string name);
		void		setHumanName(std::string name);
		void		setWeapon(Weapon &name);
		std::string	getHumanName(void);
		std::string	getWeaponName(void);
		void		attack();
};

레퍼런스의 장점으로 쓴 NULL포인터 예외 방지가 포인터의 장점일 수도 있다.

포인터로 Weapon을 들고 있는 HumanB는 무기를 들고 있지 않을 수 있다. 하지만 레퍼런스로 Weapon을 들고 있는 HumanA는 무조건 무기를 들고 있다.

이와같이 포인터가 필요한 상황이 있을 때 말고는 전부 레퍼런스를 사용하는걸 cpp에서 권장한다.

https://github.com/donghyun1998/cpp_module/tree/main/cpp01/ex02

 

GitHub - donghyun1998/cpp_module: cpp piscine.

cpp piscine. Contribute to donghyun1998/cpp_module development by creating an account on GitHub.

github.com

 

반응형

'<language> > c++' 카테고리의 다른 글

간단 echo server 구현 (C++)  (2) 2023.10.16
c++ class 상속, 가상함수 테이블, 추상클래스  (0) 2023.08.07
c++ 동적할당  (0) 2023.07.06
cpp 파일 컨트롤(ifstream ofstream)  (0) 2023.07.05
cpp split  (0) 2023.05.29
profile

그럴듯한 개발 블로그

@donghyk2

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!