exception-safety

C++: why this simple Scope Guard works?

别来无恙 提交于 2019-11-30 16:55:53
问题 Every looked at scope guard so far has a guard boolean variable. For example, see this discussion: The simplest and neatest c++11 ScopeGuard But a simple guard works (gcc 4.9, clang 3.6.0): template <class C> struct finally_t : public C { finally_t(C&& c): C(c) {} ~finally_t() { (*this)(); } }; template <class C> static finally_t<C> finally_create(C&& c) { return std::forward<C>(c); } #define FINCAT_(a, b) a ## b #define FINCAT(a, b) FINCAT_(a, b) #define FINALLY(...) auto FINCAT(FINALY_, _

Is it safe to use emplace_back with a container of unique_ptrs?

空扰寡人 提交于 2019-11-29 03:05:29
Consider the following: std::vector<std::unique_ptr<int>> ptrsToInts; ptrsToInts.emplace_back(new int); If reallocation occurs in the vector, and that fails (throwing std::bad_alloc ), am I "safe" or will I leak an int ? C++11 23.3.6.5 [vector.modifiers]/1 says: If an exception is thrown other than by the copy constructor, move constructor, assignment operator, or move assignment operator of T or by any InputIterator operation there are no effects. which seems to indicate that this is a potential problem. That is, if there are "no effects", then no unique_ptr ever was constructed, and

Is it safe to use emplace_back with a container of unique_ptrs?

让人想犯罪 __ 提交于 2019-11-27 17:22:16
问题 Consider the following: std::vector<std::unique_ptr<int>> ptrsToInts; ptrsToInts.emplace_back(new int); If reallocation occurs in the vector, and that fails (throwing std::bad_alloc ), am I "safe" or will I leak an int ? C++11 23.3.6.5 [vector.modifiers]/1 says: If an exception is thrown other than by the copy constructor, move constructor, assignment operator, or move assignment operator of T or by any InputIterator operation there are no effects. which seems to indicate that this is a

The simplest and neatest c++11 ScopeGuard

血红的双手。 提交于 2019-11-26 03:55:30
问题 I\'m attempting to write a simple ScopeGuard based on Alexandrescu concepts but with c++11 idioms. namespace RAII { template< typename Lambda > class ScopeGuard { mutable bool committed; Lambda rollbackLambda; public: ScopeGuard( const Lambda& _l) : committed(false) , rollbackLambda(_l) {} template< typename AdquireLambda > ScopeGuard( const AdquireLambda& _al , const Lambda& _l) : committed(false) , rollbackLambda(_l) { _al(); } ~ScopeGuard() { if (!committed) rollbackLambda(); } inline void