Good spot!
class file {
typedef FILE *ptr;
ptr wrapped_file;
public:
file(std::string const &name, std::string const &mode =
std::string("r")) :
wrapped_file(fopen(name.c_str(), mode.c_str()))
{ }
operator ptr() const { return wrapped_file; }
~file() { if (wrapped_file) fclose(wrapped_file); }
};
-----------------------------------------------------------------------------
file f("myfile.txt", "w");
if (!f) {
fprintf(stderr, "Unable to open file\n");
return 0;
}
fprintf(f, "Hello world");
On 31/05/2017 9:36 PM, John McKown wrote:
On Wed, May 31, 2017 at 8:26 AM, David Crayford <[email protected]> wrote:
I think I should have used the term object based for non-OO languages.
Scope based finalization is a sweet spot of C++ with scoped based
destructors. I'm coding a lot of Java at the moment and having to code
finally blocks or use the try-with-resources statement is tedious. But my
point was mainly about polymorphism and how it can be implemented in
languages that have function pointers. Of course, in a language that has no
destructors or finalization you have to explicitly call a destructor.
Here is a nifty piece of C++ code that wraps the C stdio FILE structure
which implements RAII to call fclose() by using a implicit pointer
operator! It's one of the many C++ features many people are not aware of.
Props to Jerry Coffin who invented it.
|classfile {typedefFILE*ptr;ptr wrapped_file;public:file(std::string
const&name,std::string const&mode =std::string("r")):wrapped_fil
e(fopen(name.c_str(),mode.c_str())){}operatorptr()const{re
turnwrapped_file;}~file(){if(wrapped_file)fclose(wrapped_file);}};
-----------------------------------------------------------------------------
||file f("myfile.txt","w");if(!f){fprintf(stderr,"Unable to open
file\n");return0;}fprintf(f,"Hello world");|
ββ
βIt appears to me that the last section, containing code, does not have any
proper line breaks. I can't read it. And I don't know enough C++ to
reformat it. β
----------------------------------------------------------------------
For IBM-MAIN subscribe / signoff / archive access instructions,
send email to [email protected] with the message: INFO IBM-MAIN