Can i make an object in C++ specifying its memory address explicitly? This is because i am having separate ids for each of my entities (the objects). So if i can do this, i will be able to traverse through all my objects by mere pointer additions.
Consider:
I have an object with memory location x.
I want to create the next object with memory location x+(the unique id of the next object)*K
where K is the constant gap between two objects(say)
Can i make an object in C++ specifying its memory address explicitly? This is
Share
You can specify the memory using the placement
newoperator.Not really. Disregard answers that tell you to do this! You can’t do pointer arithmetics outside of an array. Just because you have 2 objects
o1ando2, one located at0x4and the other at0x5, it doesn’t mean that&o1 + 1will yield&o2. In fact, it’s undefined behavior.For this to work as expected, you can allocate the memory dynamically, or, better yet, use a
std::vectorand use iterators. (that’s what they are for)