This works in Visual C++ 2010:
My concern is the lambda argument of FILE* does not match the expected type of the cleanup function template, FILE*& after argument expansion. But it works! Is this safe, or do I need to use FILE*& in the lambda?Code:#include <boost/noncopyable.hpp> #include <stdio.h> #include <functional> #include <utility> using namespace std; template <typename T> class scoped_sentry: boost::noncopyable { T& object; function<void(T&)> cleanup; public: scoped_sentry(T&& object, function<void(T&)> cleanup) : object(object), cleanup(cleanup) {} ~scoped_sentry() { cleanup(object); } operator T&() { return object; } }; int main() { scoped_sentry<FILE*> in( fopen("test.txt", "r"), [](FILE* fp) { if (fp) fclose(fp); }); int ch; while ((ch = fgetc(in)) != EOF) putchar(ch); }



1Likes
LinkBack URL
About LinkBacks



Does a straight FILE* work?

