new & delete

malloc은 사용하는데 두 가지 불편사항이 따른다

그런데 C++에서 제공하는 키워드 new와 delete를 사용하면 이러한 불편한 점이 사라진다.

//new 키워드 사용

int *ptr1 = new int;
double *ptr2 = new double;
int *arr1 = new int[3];
double *arr2=new double[7];

//delete 키워드 사용
delete ptr1;
delete ptr2;
delete []arr1;
delete []arr2;
#include <iostream>
#include <string.h>
using namespace std;

char *MakeStrAdr(int len)
{
	//char *str=(char *)malloc(sizeof(char) * len);
	char *str=new char[len];
	return str;
}

int main(void)
{
	char *str=MakeStrAdr(20);
	strcpy(str, "I am so happy~");
	cout << str << endl;
	// free(str);
	delete []str;
	return 0;
}

이제 앞으로 C++ 에서는 malloc 과 free 함수를 호출하는 일이 없어야 한다. 특히 C++ 에서는 malloc과 free 함수의 호출이 문제가 될 수도 있다는 사실을 기억하기 바란다.

객체의 생성에서는 반드시 new & delete

문제가 되는 경우를 보자.

Class Simple
{
	public:
		Simple()
		{
			cout<<"I'm simple constructor!"<<endl;
		}
};

int main(void)
{
	cout<<"case 1: ";
	Simple *sp1=new Simple;
	
	cout<<"case 2: ";
	Simple *sp2=(Simple *)malloc(sizeof(Simple)*1);
	
	cout<<endl<<"end of main"<<endl;
	delete sp1;
	free(sp2);
	return 0;
}
//Result
case 1: I'm simple constructor!
case 2:
end of main

결론은 다음과 같다.

힙에 할당된 변수? 이제 포인터를 사용하지 않아도 접근할 수 있어요

참조자의 선언은 상수가 아닌 변수를 대상으로만 가능함을 알고 있을 것이다. C++ 에서는 new 를 사용해 만들어진 메모리 공간도 변수로 간주하여 참조자의 선언이 가능하도록 하고 있다.