简体   繁体   中英

Unsure where to delete object

I have the following class which stores pairs of dates and prices:

#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) { }
};

An object of this class is created and filled with data with the following function:

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

Given this setup, where would I call delete to free the memory allocated when creating each date object in the loadData function? My first guess was to delete the dates in A's deconstructor, but what if the dates passed to the constructor are to be used elsewhere outside of class A?

Any help with this would be much appreciated.

Unless you have very good reason to do so, forget about the pointers:

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);

}

and modify the class accordingly:

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

Then you don't have to worry about memory management. The compiler will make optimizations such that the code above performs less copies than you would imagine.

You can use a shared_ptr (from boost or tr1) for automatic memory clean up:

vector<pair<boost::shared_ptr<date>, float> > prices;

I would also suggest to make prices in loadData a std::vector, instead of an array.

The best solution for keeping pointers in a container would be using boost::shared_ptr / std::shared_ptr . Then they will destroy contained objects when, their reference count drops to 0, and you don't have to worry about where it happens.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM