Is it possible in C++ to create a new object at a specific memory location? I have a block of shared memory in which I would like to create an object. Is this possible?
When a variable is created in C, a memory address is assigned to the variable. The memory address is the location of where the variable is stored on the computer. When we assign a value to the variable, it is stored in this memory address.
And why is it useful to know the memory address? References and Pointers (which you will learn about in the next chapter) are important in C++, because they give you the ability to manipulate the data in the computer's memory - which can reduce the code and improve the performance.
C++ allows us to allocate the memory of a variable or an array in run time. This is known as dynamic memory allocation. In other programming languages such as Java and Python, the compiler automatically manages the memories allocated to variables.
You want placement new
(). It basically calls the constructor using a block of existing memory instead of allocating new memory from the heap.
Edit: make sure that you understand the note about being responsible for calling the destructor explicitly for objects created using placement new()
before you use it!
Yes. You need to use placement variant of operator new(). For example:
void *pData = ....; // memory segment having enough space to store A object A *pA = new (pData) A;
Please note that placement new does not throw exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With