0

My aim is to create a vector containing many pre-prepared (I dont have the two data members until later on but I want to allocate as much as I can in continuous memory) instances of my object in continuous memory and then later on in my program I can quickly use one of these prepared "shells" to instantiate my object quicker. Most importantly all of these objects will be located in the same continuous memory addresses.

To achieve the above I did this:

vector<MyClass*>* v = new vector<MyClass>();
v.reserve(10000);

//Later on....

// I want to create my object in the continuous memory I "reserved" 
// and have a variable name to it:

v->push_back(MyClass m(10,20));
process(m);

But I cannot get it to compile whilst still having a variable name on the object.... here is MyClass:

class MyClass{
    public:
        MyClass();
        MyClass(int a, int b);
        MyClass(const MyClass& m);
        int a;
        int b;
    private:
    //Made above example simpler by putting everything public
}
4

1 回答 1

0

我做对象池,但我不尝试将它们分配在连续的内存中,因为这不是关于内存缓存,而是关于最小化对newand的调用delete

我将使用过的对象保存在一个空闲列表中。当我不再需要一个时,我将它推入空闲列表。然后,当我需要一个时,我只需从空闲列表中弹出一个。如果空闲列表为空,那就是我new一个新列表的时候。

于 2013-10-06T01:21:18.650 回答