Having read literally dozens of answers here on the topic of lists, vectors, the new
operator, RAII and this very good description of memory allocation, I still cannot imagine a practical implementation that meets the following need. Note I am most experienced in .net and its memory management, if that helps guide any answers.
Basically, I have class (say class RecordFile {}
) that encapsulates a text file in a particular format. Each line equates to a record that I would like to add to a std::list<Record>
owned by a RecordList
instance, where the class Record
captures the data from a single line in the file.
In the RecordList
class, I have a method RecordList::Read()
that reads the file line-by-line, creating a new Record
instance and adding it to the list owned by the RecordList
instance.
In this Read()
method is a loop that iterates over the file's lines, creating the new Record
instances. Clearly once the file is read and the Read()
method finishes, I would like the list of records to persist in the RecordList
object, but I cannot see how to do this without using the 'new' operator.
How is this task intended to be performed in c++ without violating what seem like fundamental rules? In .net this would be trivial and performed exactly as said without any risk to performance or memory leakage. I understand c++ is a different beast and am trying to get to grips with it.