C# coder just wrote this simple C++ method to get text from a file:
static std::vector<std::string> readTextFile(const std::string &filePath) {
std::string line;
std::vector<std::string> lines;
std::ifstream theFile(filePath.c_str());
while (theFile.good()) {
getline (theFile, line);
lines.push_back(line);
}
theFile.close();
return lines;
}
I know this code is not efficient; the text lines are copied once as they are read and a second time when returned-by-value.
Two questions:
(1) can this code leak memory ?
(2) more generally can returning containers of objects by value ever leak memory ? (assuming the objects themselves don’t leak)
Forget about efficiency, this code is not correct. It will not read the file correctly. See the following topic to know why:
So the loop should be written as:
Now this is correct. If you want to make it efficient, profile your application first. Try see the part which takes most CPU cycles.
No.
Depends on the type of the object in the containers. In your case, the type of the object in
std::vectorisstd::stringwhich makes sure that no memory will be leaked.