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)
问题:
回答1:
You can specify the memory using the placement new
operator.
So if i can do this, i will be able to traverse through all my objects by mere pointer additions.
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 o1
and o2
, one located at 0x4
and the other at 0x5
, it doesn't mean that &o1 + 1
will 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::vector
and use iterators. (that's what they are for)
回答2:
C++ placement new operator does what you want. Just make sure you allocate them enough memory.
See: http://www.parashift.com/c++-faq-lite/dtors.html#faq-11.10
The example from above link:
char memory[sizeof(Fred)];
void* place = memory;
Fred* f = new(place) Fred();
回答3:
You can use Andrews answer and allocate an array of Objects.
In C++, You can also use a special form of the new operator to create an object at a preallocated address:
char memory[sizeof(MyClass[100])]; // memory for an array of 100 MyClass-objects
// Cast to MyClass-Array to let the compiler calculate
// the start addresses of the array elements.
MyClass * array = reinterpret_cast<MyClass *>(memory);
// create object with index 5
MyClass * pointerToSixthEntry= new (&array[5]) MyClass();
// Use the object by its index (no pointer arithmetic needed)
array[5].sayHelloWorld();
This is called placement new.
It is ugly and I wouldn't do it. If it's not really memory/runtime critical, You could think about using a STL map with the index as key. As a positive side effect, You get the tracking of used/unused IDs for free.
Using a preallocated vector might also help. Check Luchian's answers and comments.
回答4:
Qestion on your ids, are these also consecutive and no missing values?
if so
I think the std::map suits your needs, the keys (your ids) are sorted, (just insert within recursion) and you have the ability to use iterators (pointer arithmetic).
http://www.cplusplus.com/reference/stl/map/