1

我在将新位置用于连续内存时遇到了一些问题。如果有任何其他方法可以做到这一点,请指导我。
请参考我的代码。

#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;
}
4

3 回答 3

1

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

MyClass* pMyClass2 = ::new((MyClass*)pMyClass + 1)MyClass();
于 2012-03-26T10:59:07.507 回答
0

您必须在循环中调用放置 new ,该循环在 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();
    }
    // ... 
}
于 2012-03-26T10:53:28.183 回答
0

尝试:

MyClass* pMyClass1 = :: new(pMyClass)MyClass[10];   
于 2012-03-26T10:54:48.883 回答