不确定删除对象的位置

Dav*_*lke 1 c++ delete-operator

我有以下课程,存储日期和价格对:

#include <vector>
#include <utility>
#include "boost/date_time/gregorian/gregorian.hpp"

using std::vector;
using std::pair;
using boost::gregorian::date;

class A {
private:
    vector<pair<date*, float> > prices;
public:
    A(pair<date*, float> p[], int length) : prices(p, p + length) { }
};
Run Code Online (Sandbox Code Playgroud)

使用以下函数创建并填充此类的对象:

A loadData() {
    // create price array
    pair<date*, float> *prices = new pair<date*, float>[10];

    // fill array with data (normally read from a file)
    for (int i = 0; i < 10; ++i) {
        prices[i].first = new date(2012, 4, 19);
        prices[i].second = 100;
    }

    // create the object using the price array
    A result(prices, 10);

    // delete the price array (its contents have been moved to result's vector)
    delete[] prices;

    return result;
}
Run Code Online (Sandbox Code Playgroud)

鉴于此设置,在loadData函数中创建每个日期对象时,我将在何处调用delete以释放分配的内存?我的第一个猜测是删除A的解构函数中的日期,但是如果传递给构造函数的日期要在A类之外的其他地方使用呢?

任何有关这方面的帮助将非常感激.

jua*_*nza 7

除非你有充分的理由这样做,否则请忘记指针:

A loadData() {
    // create price array
    vector<pair<date, float> > prices;

    // fill array with data (normally read from a file)
    for (int i = 0; i < 10; ++i) {
        prices.push_back(make_pair(date(2012, 4, 19), 100));
    }

    // create and return the object using the price array
    return result(prices);

}
Run Code Online (Sandbox Code Playgroud)

并相应地修改类:

class A {
private:
    vector<pair<date, float> > prices;
public:
    explicit A(const std::vector<pair<date, float> >& p) : prices(p) { }
};
Run Code Online (Sandbox Code Playgroud)

那你就不用担心内存管理了.编译器将进行优化,使上面的代码执行的副本比您想象的少.