动态分配的对象生成器

时间:2016-11-05 20:05:23

标签: c++ pointers memory-management memory-leaks

看看这堂课:

//HPP
class A {
  public:
    A();
    ~A();
    B *fetchNew();

  private:
    B *currentValue;
}


//CPP
A::A() {}

A::~A {
   delete currentValue;
}

B *A::fetchNew() {
    delete currentValue;
    currentValue = new B();
    //apply magic to currentValue
    return currentValue;
}

这个类包含一个指向B类实例的指针。每次调用fetchNew()时,旧的都会被删除,一个新的被分配并且魔法被应用到它之后,在新的和闪亮的{{1}之后返回。

这种方法被频繁调用(在现实生活中,它是一种在游戏主循环中返回视图矩阵的方法,因此每帧调用一次,大约每秒60次)。

一旦A对象被删除,它将删除当前currentValue,否则会泄漏。

有没有更好的方法来实现这个目标?

编辑:

这是实际的代码,因为它有一个扭曲(只是currentValue方法):

fetchNow()

1 个答案:

答案 0 :(得分:2)

  

有没有更好的方法来实现这个目标?

我建议使用 import datetime as dt ... df1['Date'] = pd.to_datetime(df1['Date'], format="%m/%d/%Y") # ORIGINAL GROUP BY (NO CHANGE) df2 = df.groupby(['Company','Group','Period']).sum().reset_index() df2['Pct_Growth_YoY'] = df2.sort_values('Period').groupby(['Company','Group'])\ .pct_change(4) # LOCATE MAX QUARTER GROUP INDICES maxgrps = df2.groupby(['Company','Group'])['Period']\ .apply(lambda row: row[row==row.max()].index.values[0])\ .reset_index()['Period'].values.tolist() # UPDATE ONLY MAX QUARTER GROUP ROWS df2.ix[maxgrps, 'Pct_Growth_YoY'] = \ df[(df['Date'] <= (dt.datetime.today() - dt.timedelta(days=365.25))) | (df['Date'] >= dt.datetime(dt.datetime.today().year, 1, 1))]\ .groupby(['Company','Group','Period']).sum().reset_index()\ .groupby(['Company','Group']).pct_change(4)['Value']\ .iloc[maxgrps].values 而不是原始指针std::unique_ptr<B>

B*
//HPP
#include <memory>
class A {
  public:
    A();
    ~A();
    std::unique_pty<B> fetchNew();

  private:
    // You don't need that: B *currentValue;
}

这种方法有几个优点:

  • 您不必关心//CPP A::A() {} A::~A { // You don't need that: delete currentValue; } std::unique_ptr<B> A::fetchNew() { // You don't need that: delete currentValue; std::unique_ptr<B> newValue = std::make_unique<B>(); // apply magic to newValue and dereference using * or -> as with any raw pointer return newValue; }
  • 中的删除或内存泄漏
  • A结果的所有权转让在语义上是明确的
  • 这是一个更清晰的API,客户端会知道他们获得指针的所有权,如果他们需要删除该实例,则不必谜语
  • 您可以让客户灵活地确定fetchNew()实例本身的生命周期范围。

至于您编辑的添加内容,它应如下所示:

B
相关问题