为我的对象分配特定/显式的内存位置 [英] Assigning specific/explicit memory locations to my objects
问题描述
我可以在C ++中使对象明确指定其内存地址吗?这是因为我为每个实体(对象)有单独的ID.因此,如果我能做到这一点,我将能够仅通过添加指针就可以遍历所有对象. 考虑: 我有一个内存位置为x的对象. 我想创建一个下一个对象,其内存位置为x +(下一个对象的唯一ID)* K 其中K是两个物体之间的恒定间隙(例如)
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)
推荐答案
您可以使用放置new
运算符来指定内存.
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.
并非如此. 无视告诉您执行此操作的答案!您不能在数组外部进行指针算术运算.仅仅因为您有2个对象o1
和o2
,一个位于0x4
,另一个位于0x5
,并不意味着&o1 + 1
将产生&o2
.实际上,这是未定义的行为.
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.
要使此功能按预期工作,可以动态分配内存,或者更好的是使用std::vector
并使用迭代器. (这就是他们的目的)
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)
这篇关于为我的对象分配特定/显式的内存位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!