连续内存的新位置
Placement new for contiguous memory
我在为连续内存使用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();
尝试:
MyClass* pMyClass1 = :: new(pMyClass)MyClass[10];
您必须在循环中调用新的放置,该循环在10个连续的内存块上迭代:
int main()
{
void* pMyClass = ::operator new(sizeof(MyClass)*10);
MyClass* pMyClass1 = reinterpret_cast<MyClass*>(pMyClass);
for (size_t i=0; i<10; ++i) {
::new(pMyClass1++)MyClass();
}
// ...
}
相关文章:
- C++:将 UDP 袜子转移到新位置
- 将数据复制到磁盘上新位置的语法
- (虚拟)父级中的新位置
- 在 Omnet++ 中的模拟时间内更改/设置节点的新位置
- 放置新位置的错误警告
- 自复制文件到新位置tchar不兼容
- 适用于会员变量的新位置
- 通过在此指针上放置新位置重新初始化对象时未定义的行为
- 在初始化的内存上使用放置新位置是否合法
- 递归功能,以打印每个新位置以进行控制
- 是否可以在没有push_back(C++STL)的情况下使用数组初始化矢量的新位置
- 新位置的返回值
- 在不介绍图像之后,如何找到功能的新位置
- 用于指针块的新位置
- 严格的别名规则和新位置
- 将 std::unique_ptr 移动到 std::vector 中的新位置
- C++展示位置新的工作方式
- 连续内存的新位置
- 使用新位置处理内存
- c++在自制vector容器中的新位置