Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create new C++ object at specific memory address?

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?

like image 760
Chris Avatar asked Oct 12 '09 14:10

Chris


People also ask

What is memory address in C?

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.

Why use memory address in C++?

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.

What is C++ memory?

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.


2 Answers

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!

like image 117
D.Shawley Avatar answered Oct 18 '22 14:10

D.Shawley


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.

like image 23
dimba Avatar answered Oct 18 '22 14:10

dimba