如何创建从指定内存地址开始的数据结构(不使用 new)?
我以前问过类似的问题,但现在我才意识到我收到的答案并不完全是我想要的。
如果我只是有某种结构类型的指针,那么如何在不使用“new”的情况下移动到或创建从结构指针(我已为其分配地址)指定的地址开始的相同结构类型的实例。
I asked a similar question before, but I only realized now that the answer I received isn't totally what I wanted.
If I simply have a pointer of some structure type, how can I either move to, or create an instance of the same structure type starting at an address specified by the struct pointer (which I have assigned an address to) without using "new".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这就是展示位置
new
的用途:That's what placement
new
is for:如果您只考虑没有构造函数的 C,一旦您有一个指向至少与结构体一样大的内存块的指针,那么只需将该指针转换为适当的类型就足够了。
如果您谈论的是 C++,那么这取决于实际类型。无论是拼写为
struct
还是class
在这里都没有真正的区别。如果该类型有一个简单的构造函数,那么您可以使用与 C 中相同的方法,因为构造函数实际上什么也不做。如果对象有一个重要的构造函数,那么您需要调用该构造函数,并且必须通过放置 new 来完成。If you are considering only C, where there is no constructors, once you have a pointer to a block of memory that is at least as big as the struct, then just casting that pointer to the appropriate type is sufficient.
If you are talking about C++, then it depends on the actual type. Whether it is spelled as
struct
orclass
does not make a real difference here. If the type has a trivial constructor then you can use the same approach than in C, as the constructor will effectively do nothing at all. If the object has a non-trivial constructor, then you need to call the constructor, and that has to be done with placement new.我可以想到两种解决方案
使用placement new而不是new。
对于 C 风格结构,只需将结构复制到内存地址并对其进行类型转换 - 按位复制
即
为了简洁起见,我忽略了对有效内存的检查
I can think of two solutions
Use placement new instead of new.
For a C style structure simply copy the structure to the memory address and typecast it - bitwise copy
i.e.
I am ignoring check for valid memory for brevity
好的。假设你有一个A类型的结构。
如果你想将b复制到a(即复制到a的地址),你可以使用memcpy。
http://www.cplusplus.com/reference/clibrary/cstring/memcpy/。
这将使“b”的内容从a的地址开始,由
&a
给出。如果您有两种不同的结构类型,请确保两者具有相同的大小,否则您会出现意外的行为。
Okay. Let's say you have a structure of Type A.
If you want to copy b to a (i.e. to the address of a), you would use memcpy.
http://www.cplusplus.com/reference/clibrary/cstring/memcpy/.
This would make the content of "b" start at the adress of a, given by
&a
.If you have tow different structure types, ensure that both have the same size or you have unexpected behaviour.