I am new to C++ and I want to know whether following code is prone to memory leak.
Here I am using a std::ostream
pointer to redirect output to either console or to a file.
For this I am calling new operator for std::ofstream
.
#include <iostream>
#include <fstream>
int main() {
bool bDump;
std::cout << "bDump bool" << std::endl;
std::cin >> bDump;
std::ostream *osPtr;
if (bDump) {
osPtr = new std::ofstream("dump.txt");
} else {
osPtr = &std::cout;
}
*osPtr << "hello";
return 0;
}
And one more thing, I have not closed the file which I opened while calling constructor for ofstream
. Do we have any potential data loss situation here. as file is not closed.