- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
所以我最近遇到了新的展示位置,对此我有一个疑问。我知道当您想在已分配的内存上分配对象时,会使用 placement new。
假设我有一个名为 foo 的类,它有 20 个字节。
我会用它做一些操作,然后我会为名为 bar 的类调用一个 placement new,它有 10 个字节。
不属于新对象的最后 10 个字节会怎样?放置新分区是否只需要所需的内存量,在本例中为 10 字节?还是指针只携带额外的 10 个字节直到它被释放?
还有另一种情况,假设我首先开始为类 bar 分配内存,它是 10 个字节。然后我将放置 20 个字节的新类 foo。编译器会分配更多内存吗?还是我必须确保事先分配足够的内存?
最佳答案
What happens to the last 10 bytes that is not part of the new object.
什么都没有。 Placement-new 不会触及它。它不知道该内存块中是否已经存在其他内容。您可以轻松地为 2 个 bar
对象分配大小,在后 10 个字节中构造一个 bar
对象,然后在前 10 个字节中构造另一个 bar
对象字节。想一想如果 placement-new 做了一些事情超出了您提供的内存地址的范围并且它破坏了内存后半部分的 bar
会发生什么。不好。所以它不会那样做。
Does placement new partition only the amount of memory required, which is in this case 10bytes?
是的。 Placement-new 将简单地调用 bar
构造函数,将指定的内存地址作为构造函数初始化的起始地址传递给它。构造函数将只初始化它需要的内存部分。由于bar
类是10个字节,所以最多只能初始化10个字节。其余 10 个字节保持不变。
Or does the pointer just carry around the extra 10 bytes until it is deallocated.
如果分配 20 个字节并在前 10 个字节中构造一个 bar
,则剩余的 10 个字节将简单地存在于内存中的 bar
对象之后,而不是一部分bar
对象本身。你可以用这 10 个字节做任何你想做的事。
And another case, lets say I've first started of by allocating memory for class bar, which is 10 bytes. I'll then placement new class foo, which is 20 bytes. Will the compiler allocate more memory?
没有。 Placement-new 只是在您提供的内存地址处构造指定的类。您有责任确保内存足够大以容纳正在构造的类。
Or do I have to make sure to allocate enough memory beforehand?
是的。
关于c++ - 安置新的在不同的大小类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32000731/
我正在尝试在共享内存段中分配一个第三方类(不是我写的)。 不知道这个类是如何实现的,但它可能包含另一个"new"、“malloc”调用来为其需要分配内存。 这是否意味着这个新内存将不会在共享内存段内分
我是一名优秀的程序员,十分优秀!