new와 delete
2022. 4. 3. 03:18ㆍC++
new와 delete를 이해하기 위해선
힙 메모리 할당 및 소멸에 필요한 함수인 malloc과 free에 대하여 알고 있어야 한다.
2022.04.03 - [C++] - malloc & free
(int *)malloc(sizeof(int)*3);
C언어의 동적할당에는 다음 두 가지 불편함이 존재한다.
1. 할당할 대상의 정보를 무조건 바이트 크기 단위로 전달해야 한다. sizeof()
2. 반환형이 void형 포인터이기 때문에 적절한 형 변환을 거쳐야 한다. (int *)
그런데 C++에서 제공하는 키워드 new와 delete를 사용하면 이런 불편함이 사라진다.
new와 delete 사용방법은 다음과 같다.
- int 형 변수의 할당과 소멸
int *ptr1 = new int;
delete ptr1;
- double형 변수의 할당과 소멸
double *ptr2 = new double;
delete ptr2;
- int형 배열의 할당과 소멸
int *arr1 = new int[3]
delete []arr1;
- double형 배열의 할당과 소멸
double *arr2 = new double[3]
delete []arr2;
즉 처음에 언급했던 malloc 선언은 아래와 같이 바꿀 수 있다.
// (int *)malloc(sizeof(int)*3);
new int[3];
new와 malloc 동작방식에는 차이가 있기 때문에 C++에서는 new를 사용하는 것으로 한다.
#include <iostream>
#include <stdlib.h>
using namespace std;
class Example
{
public:
Example()
{
cout<<"I'm constructor"<<endl;
}
};
int main(void)
{
Example *ex1 = new Example;
// I'm constructor 출력
Example *ex2 = (Example *)malloc(sizeof(Example)*1);
// 출력 안 됨
delete(ex1);
free(ex2);
return 0;
}
'C++' 카테고리의 다른 글
Inheritance (0) | 2022.04.03 |
---|---|
Member Initializer (0) | 2022.04.03 |
malloc & free (0) | 2022.04.03 |
Reference (0) | 2022.04.03 |
template (0) | 2022.04.02 |