I have a class that delegates some responsibilities to another helper class which is abstract. When instantiating the class the user needs to provide a pointer to a concrete instance of the abstract helper class. I'm wondering who should be responsible for deleting the helper class instance, the user, or the class itself?
It seems to me that it is better for the class to delete the helper since it ensures that the lifetime of the helper class instance is the same as the lifetime of the class thats using it.
P.S. I know shared pointers can help but I'd rather avoid them here.
Specifically which is better, this:
classifier.h
class Classifier {
public:
Classifier(const Trainer* trainer);
Train(const RecordList& training_records);
~Classifier();
private:
const Trainer* trainer_;
Vector parameters_;
}
classifier.cpp
Classifier::Classifier(const Trainer* trainer)
: trainer_(trainer);
Classifier::Train(const RecordList& training_records) {
parameters = trainer_->UpdateParameters(training_records);
}
Classifier::~Classifier() {
delete trainer_;
}
main.cpp
int main() {
Classifier classifier(new SgdTrainer());
}
Or is this better?
classifier.h
class Classifier {
public:
Classifier(const Trainer* trainer);
Train(const RecordList& training_records);
private:
const Trainer* trainer_;
Vector parameters_;
}
classifier.cpp
Classifier::Classifier(const Trainer* trainer)
: trainer_(trainer);
Classifier::Train(const RecordList& training_records) {
parameters = trainer_->UpdateParameters(training_records);
}
main.cpp
int main() {
SgdTrainer trainer();
Classifier classifier(&trainer);
}