用c ++重新分配堆栈上的对象

时间:2014-11-25 15:34:40

标签: c++ object heap-memory

我来自Java,我发现某些对象非常混乱。

在我的代码中,我有一个具有Cell属性的Event类。当我创建一个新事件时,我想在不使用“new”关键字的情况下初始化单元格。代码如下。在Event的构造函数中我可以认为要做的是“currentCell = new Cell()”。有没有办法初始化currentCell而不这样做?

更一般地说,如果我有像currentEvent这样的对象,我该如何刷新它以获得不同的信息?假设currentEvent有单元格a和时间点10,现在我希望它存储单元格b和时间点12.在java中我会这样做:

Event e1 = new Event(a, 10);
e1 = new Event(b, 12);

但我想在c ++中做同样的事情而不在堆栈上放任何东西。

以下是事件头文件:

class Event {
public:
    Event();
    int getTime() { return timePoint; }
    void setTime(int newTime); 
    void setCell(Cell & newCell);
    virtual ~Event();
private:
    Cell * currentCell; //Class is made up of a pointer to a cell and a time
    int timePoint;
};

Event.cpp中的构造函数:

Event::Event()
{
    //Cell currentCell;
    currentCell = new Cell();  //don't want to use new, but do what to initialize currentCell to a blank new cell
    timePoint = rand() % 6 + 5;
}

一般问题:

priority_queue<Event, vector<Event>, CompareEvent> events;
Event firstEvent(*start, time); 
events.push(firstEvent);
Event * newEvent1; //I want to reassign newEvent1 and newEvent2 each time through the loop but would rather not have to use the heap
Event * newEvent2;

//temp int counter
int counter = 0;

while ((!(events.empty())) && (counter<5000)){

    //Get next event
    currentEvent = events.top();
    currentCell = currentEvent.getCell();
    if (currentCell->isAlive()) {

        bool canGrow = false;
        if (currentCell->selfGrows() || currentCell->withinRange()){
            canGrow = true;
        }

        if (canGrow){

            //Perform mitosis

            //Create a daughter cell and add it to the list; increment counter
            daughterCell = new Cell(*currentCell); 

            newEvent1 = new Event(*daughterCell, time, newDir);
            events.push(*newEvent1);

            }

        }
    }

2 个答案:

答案 0 :(得分:1)

  

我想初始化单元格而不使用&#34; new&#34;关键字。

初始化由构造函数完成。 new用于动态分配(在堆上)。这两个概念是正交的。所以,很明显,是的,你可以做到。

newEvent1 = new Event(*daughterCell, time, newDir);

如果您不想在堆上创建它,请在堆栈上创建一个对象:

Event newEvent1(*daughterCell, time, newDir);

不要忘记创建一个需要这些参数的合适的construtor。并检查三个规则。

答案 1 :(得分:1)

没有指向Cell的指针,只需要一个成员Cell。它将在构造包含Event对象的过程中构建。

class Event {
public:
    Event();
    int getTime() { return timePoint; }
    void setTime(int newTime); 
    void setCell(Cell & newCell);
    virtual ~Event();
private:
    Cell currentCell; // <-- no need to have this as a pointer (asterisk removed)
    int timePoint;
};