그럴듯한 개발 블로그
Published 2023. 7. 6. 18:53
c++ 동적할당 <language>/c++
반응형
//객체의 포인터를 반환하는 함수이다.
Zombie* newZombie(std::string name) {
	Zombie *zom = new Zombie(name);
	return (zom);
}

cpp에서 동적할당을 하고 싶을 땐

객체이름 *이름 = new 생성자(arg);

이런식으로 한다.

//객체 배열 포인터를 반환하는 함수이다.
Zombie* zombieHorde( int N, std::string name ) {
	Zombie *zom = new Zombie[N];
	for (int i = 0; i < N; i++)
		zom[i].setName(name);
	return (zom);
}

객체 배열을 동적할당 할 땐 생성자 안에 arg를 직접 넣을 수가 없다. 만든 후에 초기화 해 주는 모습이다.

int	main(void) {
	Zombie *zom = newZombie("alloc");
	delete zom; // 이렇게 메모리 해제 가능
}

free() 와 같은 역할을 하는 delete로 class, delete[]로 class배열의 메모리를 해제 할 수 있다.

++배열의 첫 주소 앞에 size가 저장되어 있어 배열의 size를 명시해 주지 않아도 알아서 메모리 해제가 된다.

 

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

 

GitHub - donghyun1998/cpp_module: cpp piscine.

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

github.com

 

반응형

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

c++ class 상속, 가상함수 테이블, 추상클래스  (0) 2023.08.07
c++ 레퍼런스(참조자)  (8) 2023.07.06
cpp 파일 컨트롤(ifstream ofstream)  (0) 2023.07.05
cpp split  (0) 2023.05.29
STL 해시  (0) 2023.04.06
profile

그럴듯한 개발 블로그

@donghyk2

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