gpt4 book ai didi

c++ - 放置新的连续内存

转载 作者:太空宇宙 更新时间:2023-11-04 12:11:01 25 4
gpt4 key购买 nike

我在为连续内存使用 placement new 时遇到了一些问题。请指导我,如果有任何其他方法可以做到这一点。
请引用我的代码。

#include <new>  
//================================================
class MyClass
{
private:
int ma;
public:
MyClass():ma(-1){}
};
//===========================================

int main()
{
// I am allocating the memory for holding 10 elements of MyClass on heap
void* pMyClass = ::operator new(sizeof(MyClass)*10);

//! Note :: the address of pMyClass1 and pMyClass will now point to same
//location after calling placement new

MyClass* pMyClass1 = :: new(pMyClass)MyClass();

//! Problem with this is that,
//! i can only instantiate the constructor for the base address. That is
//! pMyClass[0].
//! If i have to instantiate it for all the other instances,
//! that is pMyClass[1] to pMyClass[9], then how to do it ?
return 0;
}

最佳答案

你在pMyClass中有内存的开始,步长是sizeof(MyClass)。因此,您需要做的是例如:

MyClass* pMyClass2 = ::new((MyClass*)pMyClass + 1)MyClass();

关于c++ - 放置新的连续内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9870738/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com