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:
and modify the class accordingly:
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.