Sobes.tech
Middle+

Provide examples of practical application of the placement new operator.

sobes.tech AI

Answer from AI

  1. Placement of objects in pre-allocated memory: Useful when working with object pools or fixed-size buffers, where allocating and freeing memory on the heap is undesirable due to overhead and fragmentation.

    #include <new>
    #include <vector>
    
    class MyClass {
    public:
        int value;
        MyClass(int val) : value(val) {}
    };
    
    int main() {
        // Pre-allocate memory buffer
        std::vector<char> buffer(sizeof(MyClass));
        void* buffer_ptr = buffer.data();
    
        // Create a MyClass object in the buffer using placement new
        MyClass* obj = new(buffer_ptr) MyClass(10);
    
        // Use the object
        // obj->value == 10
    
        // Explicitly call destructor since we didn't use delete
        obj->~MyClass();
    
        return 0;
    }
    
  2. In-place initialization of objects in fixed-layout data structures: Applicable in low-level programming, embedded systems, or when working with memory mapped to hardware.

  3. Implementing custom memory allocators: Placement new allows creating objects in memory obtained from a custom allocator, without relying on standard new and delete operators.

  4. Creating objects in shared memory: Enables placing objects in shared memory segments accessible by multiple processes.

    #include <iostream>
    #include <new>
    #include <sys/ipc.h>
    #include <sys/shm.h>
    
    class SharedData {
    public:
        int counter;
        SharedData(int val) : counter(val) {}
    };
    
    int main() {
        // Obtain key for shared memory segment
        key_t key = ftok("shm_example", 65);
    
        // Create or get segment identifier
        int shmid = shmget(key, sizeof(SharedData), 0666|IPC_CREAT);
        if (shmid == -1) {
            perror("shmget");
            return 1;
        }
    
        // Attach segment to process address space
        void* shm_ptr = shmat(shmid, NULL, 0);
        if (shm_ptr == (void*)-1) {
            perror("shmat");
            return 1;
        }
    
        // Create a SharedData object in shared memory
        SharedData* data = new(shm_ptr) SharedData(0);
    
        // Detach segment
        shmdt(shm_ptr);
    
        // In another process, you can attach to this segment and access the data object
        // Note: destructor should be called explicitly
    
        return 0;
    }
    
  5. Creating polymorphic objects in a pool: When combined with a memory pool, placement new can be used to create objects of different types inheriting from a base class in pre-allocated memory blocks.