Placement new

창고지기·2025년 3월 4일
0

C++ 에서의 new는 2가지 동작을 한다
1. 메모리를 할당한다
2. 생성자를 호출한다.

delete 또한 마찬가지
1. 소멸자 호출
2. 메모리 해제

Placement new

  • 이미 할당된 메모리(메모리 풀 등)에 객체를 생성할 때
    • 생성자를 명시적으로 호출할 때
    • 메모리는 정렬하는 이유는?
      • 정렬이 되지 않은 상태로 객체를 생성하면 객체의 메모리를 침범하는 등의 문제가 생길 수 있다.
        (사실 경험이 없어서 잘 모르겠음)
  • 소멸자를 반드시 명시적으로 호출해 주어야한다.
// within any block scope...
{
    // Statically allocate the storage with automatic storage duration
    // which is large enough for any object of type “T”.
    alignas(T) unsigned char buf[sizeof(T)];
 
    T* tptr = new(buf) T; // Construct a “T” object, placing it directly into your 
                          // pre-allocated storage at memory address “buf”.
 
    tptr->~T();           // You must **manually** call the object's destructor
                          // if its side effects is depended by the program.
}                         // Leaving this block scope automatically deallocates “buf”.
profile
일단 창고에 넣어놓으면 언젠가는 쓰겠지

0개의 댓글

관련 채용 정보