David Thielke
David Thielke

Reputation: 197

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.

Upvotes: 1

Views: 88

Answers (3)

juanchopanza
juanchopanza

Reputation: 227628

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.

Upvotes: 7

Rafał Rawicki
Rafał Rawicki

Reputation: 22710

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.

Upvotes: 1

Ralph
Ralph

Reputation: 5232

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.

Upvotes: 1

Related Questions