My c++ program uses many file pointers and has many return statements.
To avoid reaching a return statement without closing all open file pointers, i wrote this class, based upon the assumption that I am guaranteed that all objects' destructors are automatically called, when reaching a return statement.
Is my assumption true?
And is it good code?
Constructor and destructor in File_pointer.cpp
File_pointer::File_pointer(string filename)
{
fptr.open(filename.c_str());
};
File_pointer::~File_pointer()
{
fptr.close();
};
Example of implementation
int main ()
{
File_pointer myfile("myfile.txt");
int x = 2;
switch(x)
{
case 1: return x;
case 2: return x;
default:
break;
};
return 0;
}
Yes; all objects with automatic storage duration have their destructors called when they go out of scope.
To clarify, an automatic object is a non-static local object that wasn't dynamically allocated.
That's subjective. But what I will say is that relying on scoping to automatically invoke destructors is a very common C++ idiom, known by the bizarre name of resource acquisition is initialisation (RAII).
Classes like
std::ofstream
already use RAII; their destructor automatically closes the file. So if yourfptr
is astd::ofstream
, for instance, then your wrapper class is entirely superfluous.