프로그래밍
new
lancelot50
2022. 8. 13. 14:12
- new / delete
#include<iostream>
class Point
{
int x, y, z;
public:
Point(int a, int b, int c) : x{ a }, y{ b }, z(c) { std::cout << "Point()" << std::endl; }
~Point() { std::cout << "~Point()" << std::endl; }
};
int main()
{
Point* p1 = new Point(1, 2, 3);
delete p1;
void* p = operator new(sizeof(Point)); // 1. 메모리할당
Point* p2 = new(p) Point(1, 2, 3 ); // 2. 생성자 호출
std::cout << p<< std::endl;
p2->~Point(); // 1. 소멸자호출
operator delete(p); // 2. 메모리 해지
}
- 생성자의 명시적 호출
#include<iostream>
#include<memory>
class Point
{
int x, y, z;
public:
Point(int a, int b, int c) : x{ a }, y{ b }, z(c) { std::cout << "Point()" << std::endl; }
~Point() { std::cout << "~Point()" << std::endl; }
void set() { std::cout << x <<", "<< y <<", " << z << std::endl; }
};
int main()
{
void* p1 = operator new(sizeof(Point)); // 1. 메모리할당
Point* p2 = new(p1) Point(1, 2, 3 ); // 2. 생성자 호출
operator delete(p1);
Point* p3 =static_cast<Point*>(operator new(sizeof(Point)));
std::construct_at(p3, 1, 2, 3);
operator delete(p3);
}
- 객체를 생성/파괴 하는 방법
- 방법 1. new / delete 사용
- 방법 2. 메모리 할당과 생성자 호출을 분리
- 왜 메모리 할당과 생성자 호출을 분리하는가?
- new Point[3];
- Point 타입에는 반드시 디폴트 생성자가 있어야 한다.
- 디폴트 생성자가 없다면 에러.
- new Point[3]{ {0,0}, {0,0}, {0,0} };
- C++11 부터 가능
- 3개가 아니라 개수가 커진다면?
- 메모리 할당과 생성자 호출을 분리하면 편리하다.
- new Point[3];
- vector 와 placement new
#include<iostream>
#include<vector>
struct X
{
X() { std::cout << __FUNCSIG__<<" get resource" << std::endl; }
~X() { std::cout << __FUNCSIG__<<" release resource" << std::endl; }
};
int main()
{
std::vector<X> v(10);
std::cout << "----------" << std::endl;
v.resize(7);
std::cout << "----------" << std::endl;
std::cout << v.size()<< std::endl;
std::cout << v.capacity() << std::endl;
std::cout << "----------" << std::endl;
v.resize(8);
std::cout << "----------" << std::endl;
std::cout << v.size() << std::endl;
std::cout << v.capacity() << std::endl;
}