C 11范围出门,好主意?

我已经为C11编写了一个小型实用程序类,它用作监视器,以便更容易地处理异常安全和类似的事情。

似乎有点像黑客。但是我感到惊讶,我还没有看到其他地方使用C 11功能。我觉得boost有一些与C98相似的东西。

但这是一个好主意吗?还是有我错过的潜在问题?升压还是类似的解决方案(有C 11功能)?

    namespace detail 
    {
        template<typename T>
        class scope_exit : boost::noncopyable
        {
        public:         
            explicit scope_exit(T&& exitScope) : exitScope_(std::forward<T>(exitScope)){}
            ~scope_exit(){try{exitScope_();}catch(...){}}
        private:
            T exitScope_;
        };          

        template <typename T>
        scope_exit<T> create_scope_exit(T&& exitScope)
        {
            return scope_exit<T>(std::forward<T>(exitScope));
        }
    }


#define _UTILITY_EXIT_SCOPE_LINENAME_CAT(name, line) name##line
#define _UTILITY_EXIT_SCOPE_LINENAME(name, line) _UTILITY_EXIT_SCOPE_LINENAME_CAT(name, line)
#define UTILITY_SCOPE_EXIT(f) const auto& _UTILITY_EXIT_SCOPE_LINENAME(EXIT, __LINE__) = ::detail::create_scope_exit(f)

它使用了像。

int main () 
{
  ofstream myfile;
  myfile.open ("example.txt");
  UTILITY_SCOPE_EXIT([&]{myfile.close();}); // Make sure to close file even in case of exception
  myfile << "Writing this to a file.\n"; // Imagine this could throw
  return 0;
}

But is it a good idea?

当然。相关话题是RAII paradigm

Or are there
potential problems I have missed?

你不处理例外。

Is
there already a similar solution (with
C++0x features) in boost or similar?

Alexandrescu很久以前就提出了ScopeGuard。 Boost和std :: tr1都有一个名为scoped_ptrshared_ptr(带有自定义删除器)的东西,可以让你完成这个任务。

翻译自:https://stackoverflow.com/questions/3669833/c11-scope-exit-guard-a-good-idea

转载注明原文:C 11范围出门,好主意?