C++
C++ 동적할당
WantAirpod
2020. 7. 14. 17:34
반응형
1.new와 delete란?
C언어에서 동적할당 malloc과 free와 동일한 역할을 함.
new를 사용해서 힙에 동적할당하고 delete를 사용하여 해제
#include <iostream>
using namespace std;
struct Po
{
int a;
int b;
};
int main()
{
//C style
Po* ptr = (Po*)malloc(sizeof(Po));
free(ptr);
//C++ style
Po* ptr = new Po;
delete ptr;
return 0;
}
2.new와 delete란 ?
하지만 malloc과 new는 같지 않다.
c++의 new는 훨씬 다양한 것을 해줌.
new는 힙에 메모리할당을 해주고 생성자를 호출해주며 해당 타입으로 변환.
new
- 메모리 할당
- 생성자 호출
- 타입변환
delete
- 소멸자 호출
- 메모리 해제
#include <iostream>
using namespace std;
struct Po
{
int a;
int b;
};
class po2
{
public:
po2()
{
cout << "2) new에 의해서 생성자 호출됨 " << endl;
}
~po2()
{
cout << "3) delete에 의해 소멸자 호출됨" << endl;
}
};
int main()
{
//C style
Po* ptr = (Po*)malloc(sizeof(Po));
free(ptr);
//C++ style
Po* ptr2 = new Po;
delete ptr2;
//C style
po2* ptr3 = (po2*)malloc(sizeof(po2));
cout << "1) malloc - 메모리 할당 끝 :생성자는 불름?" << endl;
free(ptr3);
//C++ style
po2* ptr4 = new po2();
cout << "1)malloc -= 메모리 할당끝 : 생성자는 ?" << endl;
delete (ptr4);
return 0;
}
반응형