### C++ Example: Using Boost Scope Guards in a Network Receiver Source: https://www.boost.org/doc/libs/latest/libs/scope/doc/html/scope/scope_guards Demonstrates the usage of `scope_exit`, `scope_success`, and `scope_fail` within a C++ class for processing network requests. `scope_exit` logs processing time, `scope_fail` handles disconnection on exceptions, and `scope_success` sends the response upon successful completion. This example highlights RAII for managing resources and actions across different execution paths. ```c++ // A network request receiver class receiver { // A network connection connection m_conn; // A collection of sessions, searchable by session id std::map< std::string, session > m_sessions; public: // Processes a network request and sends a response void process_request(request const& req) { const auto start_time = std::chrono::steady_clock::now(); boost::scope::scope_exit time_guard([start_time] { // Log the amount of time it took to process the request const auto finish_time = std::chrono::steady_clock::now(); std::clog << "Request processed in " << std::chrono::duration_cast< std::chrono::milliseconds >(finish_time - start_time).count() << " ms" << std::endl; }); response resp; boost::scope::scope_fail failure_guard([&] { // Disconnect in case of exceptions m_conn.disconnect(); // doesn't throw }); boost::scope::scope_success success_guard([&] { // Send a response that was populated while processing the request m_conn.send_message(resp); }); // Validate the request and populate the response based on the contents of the request if (req.start_line().version > max_supported_version) { resp.start_line().version = max_supported_version; resp.start_line().set_status(protocol_version_not_supported); return; } resp.start_line().version = req.start_line().version; auto it_cseq = req.headers().find(cseq_header); if (it_cseq == req.headers().end()) { resp.start_line().set_status(bad_request); resp.set_body(mime::text_plain, "CSeq not specified"); return; } resp.headers().add(cseq_header, *it_cseq); auto it_session_id = req.headers().find(session_id_header); if (it_session_id == req.headers().end()) { resp.start_line().set_status(bad_request); resp.set_body(mime::text_plain, "Session id not specified"); return; } resp.headers().add(session_id_header, *it_session_id); // Find the session to forward the request to auto it_session = m_sessions.find(*it_session_id); if (it_session == m_sessions.end()) { resp.start_line().set_status(session_not_found); return; } // Process the request in the session and complete populating the response it_session->second.process_request(req, resp); } }; ``` -------------------------------- ### POSIX File Descriptor with unique_resource (C++) Source: https://www.boost.org/doc/libs/latest/libs/scope/doc/html/scope/unique_resource Demonstrates the initial setup of a unique_resource for a POSIX file descriptor without resource traits, highlighting potential pitfalls with the default constructor and reset function. ```cpp std::experimental::unique_resource< int, int (*)(int) > fd(-1, &close); // Potential incorrect usage: // std::experimental::unique_resource< int, int (*)(int) > fd = std::experimental::make_unique_resource_checked(-1, -1, &close); // fd.release(); // mark the resource unallocated // fd.reset(-1); // fd.reset(); // fd = std::experimental::make_unique_resource_checked(-1, -1, &close); ``` -------------------------------- ### Scope Exit Guard Example (C++11) Source: https://www.boost.org/doc/libs/latest/libs/scope/index Demonstrates using `boost::scope::make_scope_exit` to ensure variables are reset when a scope is exited, either normally or due to an exception. This is useful for cleanup operations. ```cpp class adder { int x, y; public: // Computes a sum of integers int compute() { // Reset variables on return or exception auto cleanup = boost::scope::make_scope_exit([this] { x = 0; y = 0; }); long long int sum = static_cast< long long int >(x) + static_cast< long long int >(y); if (sum < std::numeric_limits< int >::min() || sum > std::numeric_limits< int >::max()) { throw std::overflow_error("Integer overflow"); } return static_cast< int >(sum); } }; ``` -------------------------------- ### Scope Exit Guard Example (C++17) Source: https://www.boost.org/doc/libs/latest/libs/scope/index Illustrates the C++17 syntax for scope exit guards using `BOOST_SCOPE_DEFER`. This macro provides a more concise way to define actions that execute upon scope exit, similar to `make_scope_exit`. ```cpp class adder { int x, y; public: // Computes a sum of integers int compute() { // Reset variables on return or exception. // Anonymous scope guard. BOOST_SCOPE_DEFER [this] { x = 0; y = 0; }; long long int sum = static_cast< long long int >(x) + static_cast< long long int >(y); if (sum < std::numeric_limits< int >::min() || sum > std::numeric_limits< int >::max()) { throw std::overflow_error("Integer overflow"); } return static_cast< int >(sum); } }; ``` -------------------------------- ### Scope Fail Guard Example (C++17) Source: https://www.boost.org/doc/libs/latest/libs/scope/index Demonstrates the C++17 approach to scope fail guards using `boost::scope::scope_fail`. This RAII-style mechanism guarantees that the provided lambda is executed if the scope is exited due to an exception. ```cpp template< typename Object > class collection { std::set< Object > objects; public: // Adds a new object to the collection Object& add_object() { auto it = objects.emplace(); // Revert object insertion on exception boost::scope::scope_fail cleanup{[this, it] { objects.erase(it); }}; // Throws on error it->on_added(*this); return *it; } }; ``` -------------------------------- ### Scope Fail Guard Example (C++11) Source: https://www.boost.org/doc/libs/latest/libs/scope/index Shows how to use `boost::scope::make_scope_fail` to revert an operation (like erasing an element from a set) if an exception occurs during scope execution. This ensures data consistency. ```cpp template< typename Object > class collection { std::set< Object > objects; public: // Adds a new object to the collection Object& add_object() { auto it = objects.emplace(); // Revert object insertion on exception auto cleanup = boost::scope::make_scope_fail([this, it] { objects.erase(it); }); // Throws on error it->on_added(*this); return *it; } }; ``` -------------------------------- ### Using BOOST_SCOPE_DEFER with std::function for Dynamic Cleanup Source: https://www.boost.org/doc/libs/latest/libs/scope/doc/html/scope/scope_guards This example demonstrates using the BOOST_SCOPE_DEFER macro with std::function to achieve run-time scope exit actions. A non-empty function wrapper is initially created, and the actual cleanup logic is assigned later. Note that this approach requires a variable name for the function wrapper and still carries the potential exception risks associated with std::function. ```cpp // Create a non-empty function wrapper that does nothing std::function< void() > cleanup_func = [] {}; // Create a scope guard that refers to the function wrapper BOOST_SCOPE_DEFER std::ref(cleanup_func); // Later in the program, initialize the function wrapper if (cond) { cleanup_func = [] { std::cout << "cond is true" << std::endl; }; } else { cleanup_func = [] { std::cout << "cond is false" << std::endl; }; } ``` -------------------------------- ### C++ Scope Guard Capturing by Reference (Good Example) Source: https://www.boost.org/doc/libs/latest/libs/scope/doc/html/scope/scope_guards Provides a solution to the reference capturing issue in scope guards. By ensuring the scope guard's action executes before the captured variable is invalidated (e.g., by moving it out of scope), the problem is avoided. This example moves the scope guard's execution to a nested scope. ```cpp #include #include #include #include // Assume process() is a function that may consume the unique_ptr void process(int val) { /* ... */ } std::unique_ptr< int > good(std::unique_ptr< int > ptr) { assert(ptr != nullptr); { boost::scope::scope_exit guard{[&] // Captures ptr by reference { std::cout << "processed: " << *ptr << std::endl; }}; process(*ptr); } // <- scope guard action runs here, before ptr is moved-from return ptr; } ``` -------------------------------- ### Insert Two Containers with Rollback using Boost.Scope Source: https://www.boost.org/doc/libs/latest/libs/scope/doc/html/scope/scope_guards Demonstrates flexible scope guard activation in Boost.Scope by managing rollback operations for two container insertions. The example creates an initially inactive scope guard for vector insertion and conditionally activates a set insertion guard. Both guards are only armed when their respective insertions succeed, ensuring atomicity. ```cpp void insert_two(std::vector< int >* pv, std::set< int >& set, int value) { // Initially inactive scope guard boost::scope::scope_fail pv_rollback([pv] { pv->pop_back(); }, false); if (pv) { pv->push_back(value); // may throw pv_rollback.set_active(true); // activate the scope guard } auto [it, inserted] = set.insert(value); // may throw // Initially active scope guard, if a new element was inserted, otherwise inactive boost::scope::scope_fail set_rollback([&set, &it] { set.erase(it); }, inserted); on_inserted(); // may throw } ``` -------------------------------- ### Scope Exit with Automatic Cleanup - C++11 Source: https://www.boost.org/doc/libs/latest/libs/scope/doc/html/index Demonstrates using make_scope_exit() to automatically reset variables upon leaving scope or throwing exceptions. This example shows a class method that uses a scope guard to ensure cleanup of integer variables regardless of how the function exits, preventing resource leaks or undefined state. ```cpp class adder { int x, y; public: // Computes a sum of integers int compute() { // Reset variables on return or exception auto cleanup = boost::scope::make_scope_exit([this] { x = 0; y = 0; }); long long int sum = static_cast< long long int >(x) + static_cast< long long int >(y); if (sum < std::numeric_limits< int >::min() || sum > std::numeric_limits< int >::max()) { throw std::overflow_error("Integer overflow"); } return static_cast< int >(sum); } }; ``` -------------------------------- ### C++ Scope Guard Capturing by Reference (Bad Example) Source: https://www.boost.org/doc/libs/latest/libs/scope/doc/html/scope/scope_guards Demonstrates a common pitfall when using scope guards with lambdas capturing by reference. If the captured variable is moved or invalidated before the scope guard's action is executed, it can lead to undefined behavior. This example shows a case where std::unique_ptr is moved. ```cpp #include #include #include #include // Assume process() is a function that may consume the unique_ptr void process(std::unique_ptr p) { /* ... */ } void process(int val) { /* ... */ } void bad(std::unique_ptr< int > ptr) { assert(ptr != nullptr); boost::scope::scope_exit guard{[&] // Captures ptr by reference { std::cout << "processed: " << *ptr << std::endl; }}; process(std::move(ptr)); // ptr is moved, becoming null } std::unique_ptr< int > bad(std::unique_ptr< int > ptr) { assert(ptr != nullptr); boost::scope::scope_exit guard{[&] // Captures ptr by reference { std::cout << "processed: " << *ptr << std::endl; }}; process(*ptr); return ptr; // Moves from ptr, leaving it null } ``` -------------------------------- ### Access Resource Object with get() Source: https://www.boost.org/doc/libs/latest/libs/scope/doc/html/doxygen/reference/classboost_1_1scope_1_1unique__resource Returns a const reference to the managed resource object. This allows inspection and use of the resource without transferring ownership or affecting the deleter. ```C++ resource_type const & get() const noexcept; ``` -------------------------------- ### Scope Fail with Constructor Syntax - C++17 Source: https://www.boost.org/doc/libs/latest/libs/scope/doc/html/index Demonstrates the C++17 constructor-based syntax for scope_fail guards. Provides the same exception-only cleanup functionality as make_scope_fail() but with a more intuitive instantiation pattern. ```cpp template< typename Object > class collection { std::set< Object > objects; public: // Adds a new object to the collection Object& add_object() { auto it = objects.emplace(); // Revert object insertion on exception boost::scope::scope_fail cleanup{[this, it] { objects.erase(it); }}; // Throws on error it->on_added(*this); return *it; } }; ``` -------------------------------- ### Include Headers for Boost Scope Guards Source: https://www.boost.org/doc/libs/latest/libs/scope/doc/html/scope/scope_guards Includes the necessary Boost headers for using scope_exit, scope_success, and scope_fail. These headers provide the definitions for the scope guard classes. ```c++ #include #include #include ``` -------------------------------- ### Variadic Templates and Argument Packs in Boost.ScopeExit and Boost.Scope Source: https://www.boost.org/doc/libs/latest/libs/scope/doc/html/scope/scope_guards Demonstrates handling variadic templates and argument packs for scope exit actions. Boost.ScopeExit uses `BOOST_SCOPE_EXIT_ALL`, while Boost.Scope utilizes standard C++ lambda captures. ```C++ template< typename... Args > void foo(Args&&... args) { BOOST_SCOPE_EXIT_ALL(&args...) { std::cout << "Params: " << boost::tuples::tie(args...) << std::endl; }; } ``` -------------------------------- ### Synopsis of scope_exit Class Template Source: https://www.boost.org/doc/libs/latest/libs/scope/doc/html/doxygen/reference/classboost_1_1scope_1_1scope__exit This snippet provides the synopsis for the `boost::scope::scope_exit` class template. It outlines the template parameters, constructors, member functions like `active`, `set_active`, and the destructor. It's defined in the `` header. ```cpp // In header: template class scope_exit { public: // public member functions template explicit scope_exit(F &&, bool = true); template explicit scope_exit(F &&, C &&, bool = true); scope_exit(scope_exit &&); scope_exit & operator=(scope_exit &&) = delete; scope_exit(scope_exit const &) = delete; scope_exit & operator=(scope_exit const &) = delete; ~scope_exit(); bool active() const noexcept; void set_active(bool) noexcept; }; ``` -------------------------------- ### Non-Throwing Scope Exit Actions with Pre-initialized Guards Source: https://www.boost.org/doc/libs/latest/libs/scope/doc/html/scope/scope_guards This snippet illustrates a recommended non-throwing method for setting up scope exit actions. Inactive scope guards are pre-initialized for different execution paths. One of these guards is then activated at run time, ensuring that the activation process itself does not throw exceptions. This is useful when the scope guard must revert an operation that might have failed. ```cpp // Create inactive scope guards for both branches boost::scope::scope_exit cleanup_true([] { std::cout << "cond is true" << std::endl; }, false); boost::scope::scope_exit cleanup_false([] { std::cout << "cond is false" << std::endl; }, false); // Later in the program, activate one of the scope guards. // This won't throw. if (cond) cleanup_true.set_active(true); else cleanup_false.set_active(true); ``` -------------------------------- ### Dereference Resource with operator*() Source: https://www.boost.org/doc/libs/latest/libs/scope/doc/html/doxygen/reference/classboost_1_1scope_1_1unique__resource Dereferences the managed resource by invoking operator* on it. Requires the resource to be dereferenceable. Returns the result of dereferencing the resource object as if by calling *get(). May throw if dereferencing the resource itself throws. ```C++ auto operator*() const; ``` -------------------------------- ### Dereference Resource with operator->() Source: https://www.boost.org/doc/libs/latest/libs/scope/doc/html/doxygen/reference/classboost_1_1scope_1_1unique__resource Provides pointer-like indirection to the managed resource. Requires the resource to be dereferenceable. Returns a reference to the resource object by calling get(). For non-pointer resource types, the compiler chains operator-> calls until a pointer is obtained. ```C++ resource_type const & operator->() const noexcept; ``` -------------------------------- ### File Write with Scope Guard for Error Handling (C++) Source: https://www.boost.org/doc/libs/latest/libs/scope/index Demonstrates writing strings to a file using a scope guard to ensure cleanup (file closing and deletion) in case of errors. The guard is deactivated upon successful completion. ```cpp // Set a scope guard to remove the partially written file // in case of error - exception or not boost::scope::scope_exit remove_guard{[&file, &filename] { file.close(); // close the file to allow remove() to succeed on Windows std::remove(filename.c_str()); }}; bool first = true; for (auto const& str : strings) { if (!first) file << ','; else first = false; file << '"' << str << '"'; if (file.fail()) return false; } file << std::endl; if (file.fail()) return false; // Commit the operation remove_guard.set_active(false); return true; } ``` -------------------------------- ### File Descriptor Deleter and File Operations with unique_resource (C++) Source: https://www.boost.org/doc/libs/latest/libs/scope/doc/html/scope/unique_resource Demonstrates a custom deleter for POSIX file descriptors and functions to open, read, and compare file contents using `boost::scope::unique_resource`. This snippet highlights RAII for file handling, ensuring resources are properly managed even in the presence of errors or exceptions. ```cpp #include #include #include #include #include #include #include // A deleter for POSIX-like file descriptors struct fd_deleter { void operator() (int fd) const noexcept { if (fd >= 0) close(fd); } }; // Opens a file with the given filename for reading and returns wrapped file descriptor boost::scope::unique_resource< int, fd_deleter > open_file(std::string const& filename) { boost::scope::unique_resource< int, fd_deleter > file(open(filename.c_str(), O_RDONLY)); if (file.get() < 0) { int err = errno; throw std::system_error(err, std::generic_category(), "Failed to open file " + filename); } return file; } // Reads contents of a file denoted by fd into buffer and returns the number of read bytes std::size_t read_file(int fd, unsigned char* buf, std::size_t size) { std::size_t total_read_size = 0; while (total_read_size < size) { ssize_t read_size = read(fd, buf + total_read_size, size - total_read_size); if (read_size < 0) { int err = errno; if (err == EINTR) continue; throw std::system_error(err, std::generic_category(), "Failed to write data"); } if (read_size == 0) { // End of file break; } total_read_size += read_size; } return total_read_size; } // Compares contents of two files for equality bool equal_files(std::string const& filename1, std::string const& filename2) { // Create unique resource wrappers for files auto file1 = open_file(filename1); auto file2 = open_file(filename2); // Use them to read file contents constexpr std::size_t buf_size = 1024; unsigned char buf1[buf_size]; unsigned char buf2[buf_size]; while (true) { std::size_t size1 = read_file(file1.get(), buf1, buf_size); std::size_t size2 = read_file(file2.get(), buf2, buf_size); if (size1 != size2) { // File sizes are different return false; } if (std::memcmp(buf1, buf2, size1) != 0) { // File contents are different return false; } if (size1 < buf_size) { // Reached end of both files simultaneously and contents matched break; } } // Files have equal contents return true; } ``` -------------------------------- ### POSIX File Descriptor with unique_resource and Resource Traits (C++) Source: https://www.boost.org/doc/libs/latest/libs/scope/doc/html/scope/unique_resource Illustrates the correct usage of unique_resource with custom resource traits (fd_resource_traits) for POSIX file descriptors, ensuring proper handling of unallocated states and demonstrating the effect on constructor and reset operations. ```cpp boost::scope::unique_resource< int, int (*)(int), boost::scope::fd_resource_traits > fd(-1, &close); assert(!fd.allocated()); fd.reset(-1); assert(!fd.allocated()); ``` -------------------------------- ### Using scope_exit for File Handling in C++ Source: https://www.boost.org/doc/libs/latest/libs/scope/doc/html/index This snippet demonstrates how to use boost::scope::scope_exit to ensure a file is closed and removed in case of errors during file writing. It takes a vector of strings, writes them to a file, and sets up a guard to clean up the partially written file if an exception occurs or the operation fails. ```cpp // Set a scope guard to remove the partially written file // in case of error - exception or not boost::scope::scope_exit remove_guard{[&file, &filename] { file.close(); // close the file to allow remove() to succeed on Windows std::remove(filename.c_str()); }}; bool first = true; for (auto const& str : strings) { if (!first) file << ','; else first = false; file << '"' << str << '"'; if (file.fail()) return false; } file << std::endl; if (file.fail()) return false; // Commit the operation remove_guard.set_active(false); return true; } ``` -------------------------------- ### fd_resource_traits: POSIX File Descriptor Traits (C++) Source: https://www.boost.org/doc/libs/latest/libs/scope/doc/html/doxygen/reference/structboost_1_1scope_1_1fd__resource__traits Provides resource traits for POSIX-like file descriptors. Includes functions to create a default file descriptor value and to check if a file descriptor is currently allocated or valid. This is part of the Boost scope library. ```cpp #include struct fd_resource_traits { static int make_default() noexcept; static bool is_allocated(int fd) noexcept; }; ``` ```cpp static int make_default() noexcept; // Creates a default fd value. ``` ```cpp static bool is_allocated(int fd) noexcept; // Tests if the fd is allocated (valid) ``` -------------------------------- ### Unique Resource RAII Wrapper in C++ Source: https://www.boost.org/doc/libs/latest/libs/scope/doc/html/doxygen/reference/classboost_1_1scope_1_1unique__resource This C++ code defines the synopsis for the `boost::scope::unique_resource` class template. It acts as an RAII wrapper for automatically reclaiming arbitrary resources, ensuring a deleter is called on destruction. It supports move semantics, explicit construction, and optional resource traits for optimized management. ```cpp // In header: template class unique_resource { public: // public member functions unique_resource(); template unique_resource(default_resource_t, D &&); template explicit unique_resource(R &&); template unique_resource(R &&, D &&); unique_resource(unique_resource const &) = delete; unique_resource & operator=(unique_resource const &) = delete; unique_resource(unique_resource &&); unique_resource & operator=(unique_resource &&); ~unique_resource(); explicit operator bool() const noexcept; bool allocated() const noexcept; resource_type const & get() const noexcept; deleter_type const & get_deleter() const noexcept; void release() noexcept; void reset(); template void reset(R &&); resource_type const & operator->() const noexcept; auto operator*() const; void swap(unique_resource &); // friend functions void swap(unique_resource &, unique_resource &); }; ``` -------------------------------- ### Open File with Resource Checking - Boost.Scope unique_resource Source: https://www.boost.org/doc/libs/latest/libs/scope/doc/html/scope/unique_resource A factory function that opens a file and returns a wrapped file descriptor using make_unique_resource_checked. This function automatically validates whether the file descriptor is valid, throwing a system_error exception if the open() call fails. It demonstrates proper error handling for resource allocation failures. ```C++ // Opens a file with the given filename for reading and returns wrapped file descriptor boost::scope::unique_resource< int, fd_deleter > open_file(std::string const& filename) { auto file = boost::scope::make_unique_resource_checked( open(filename.c_str(), O_RDONLY), -1, fd_deleter()); if (!file.allocated()) { int err = errno; throw std::system_error(err, std::generic_category(), "Failed to open file " + filename); } return file; } ``` -------------------------------- ### Generate Random Bytes with Unique Resource Wrapper (C++) Source: https://www.boost.org/doc/libs/latest/libs/scope/index Generates random bytes using the system's random number generator (/dev/urandom). It utilizes `boost::scope::unique_resource` to manage the file descriptor, ensuring it's closed automatically. Error handling for file opening and reading is included. ```cpp // Fills the buffer with random bytes from system RNG. Returns 0 on success, otherwise an error code. int get_random_bytes(unsigned char* bytes, std::size_t size) { // Open RNG device and wrap the returned POSIX file descriptor in unique_resource. // This wrapper will automatically close the file descriptor upon destruction by invoking fd_deleter on it. boost::scope::unique_resource< int, boost::scope::fd_deleter, boost::scope::fd_resource_traits > fd(open("/dev/urandom", O_RDONLY)); // fd_resource_traits allows the unique_resource to recognize when open() returns a valid file descriptor // and when it fails and returns -1. In the latter case, the constructed unique_resource is unallocated, // which we test below. if (!fd) return errno; // Read random bytes until the buffer is filled or an error occurs std::size_t read_size = 0u; while (read_size < size) { ssize_t res = read(fd.get(), bytes + read_size, size - read_size); if (res < 0) { int err = errno; if (err == EINTR) continue; return err; } if (res == 0) return ENODATA; read_size += res; } return 0; } ``` -------------------------------- ### File Comparison Loop - Check Equal Contents with Buffers Source: https://www.boost.org/doc/libs/latest/libs/scope/doc/html/scope/unique_resource A loop structure that compares two files byte-by-byte using buffers. It reads chunks from both files and returns false if contents differ, or breaks when both files end with equal contents. This snippet represents the core comparison logic used in file validation routines. ```C++ // File contents are different return false; } if (size1 < buf_size) { // Files have ended. At this point we know they have equal contents. break; } } return true; ``` -------------------------------- ### Basic Scope Exit in Boost.ScopeExit and Boost.Scope Source: https://www.boost.org/doc/libs/latest/libs/scope/doc/html/scope/scope_guards Demonstrates the basic functionality of executing code at scope exit using both Boost.ScopeExit macros and Boost.Scope's `scope_exit` guard or `BOOST_SCOPE_DEFER`. ```C++ BOOST_SCOPE_EXIT(void) { std::cout << "Hello, World!" << std::endl; } BOOST_SCOPE_EXIT_END; ``` ```C++ boost::scope::scope_exit guard([] { std::cout << "Hello, World!" << std::endl; }); ``` ```C++ BOOST_SCOPE_DEFER [] { std::cout << "Hello, World!" << std::endl; }; ``` -------------------------------- ### Boost Scope Error Code Checker Synopsis Source: https://www.boost.org/doc/libs/latest/libs/scope/doc/html/doxygen/reference/classboost_1_1scope_1_1error__code__checker The synopsis for the boost::scope::error_code_checker class template, used for checking error codes. It includes the necessary header and the template's structure. ```cpp // In header: template class error_code_checker { public: // types typedef bool result_type; // Predicate result type. // public member functions explicit error_code_checker(ErrorCode &) noexcept; result_type operator()() const noexcept; }; ``` -------------------------------- ### unique_resource Constructors - C++ Source: https://www.boost.org/doc/libs/latest/libs/scope/doc/html/doxygen/reference/classboost_1_1scope_1_1unique__resource Provides constructors for `unique_resource`, enabling the creation of guards for unallocated or allocated resources with custom or default deleters. Requires default constructible `Resource` and `Deleter`, and constructible `Deleter` from provided types. Handles resource and deleter construction, with specific logic for exception safety during construction. ```cpp unique_resource(); ``` ```cpp template unique_resource(default_resource_t res, D && del); ``` ```cpp template explicit unique_resource(R && res); ``` ```cpp template unique_resource(R && res, D && del); ``` -------------------------------- ### Boost.Scope unique_resource Forward Declaration Source: https://www.boost.org/doc/libs/latest/libs/scope/doc/html/reference Provides a forward declaration for the `unique_resource` template. This allows `unique_resource` to be used in header files before its full definition is available, reducing compile times. Found in . ```cpp namespace boost { namespace scope { template class unique_resource; } } ``` -------------------------------- ### Safe File Writing with Scope Exit Guard (C++11) Source: https://www.boost.org/doc/libs/latest/libs/scope/index Illustrates using `boost::scope::make_scope_exit` to ensure a partially written file is removed if an error occurs during the writing process. This prevents leaving incomplete files. ```cpp // Writes a list of strings to the file, in CSV format bool save_as_csv(std::vector< std::string > const& strings, std::string const& filename) { std::ofstream file(filename.c_str(), std::ios_base::out | std::ios_base::trunc); if (!file.is_open()) return false; // Set a scope guard to remove the partially written file // in case of error - exception or not auto remove_guard = boost::scope::make_scope_exit([&file, &filename] { file.close(); // close the file to allow remove() to succeed on Windows std::remove(filename.c_str()); }); bool first = true; for (auto const& str : strings) { if (!first) file << ','; else first = false; file << '"' << str << '"'; if (file.fail()) return false; } file << std::endl; if (file.fail()) return false; // Commit the operation remove_guard.set_active(false); return true; } ``` -------------------------------- ### Define Windows Handle Resource Traits Source: https://www.boost.org/doc/libs/latest/libs/scope/doc/html/scope/unique_resource Defines resource traits for Windows HANDLE, specifying how to create a default value and check if a handle is allocated. Requires Windows API constants like INVALID_HANDLE_VALUE and NULL. ```C++ struct handle_traits { //! Returns the default resource value static HANDLE make_default() noexcept { return INVALID_HANDLE_VALUE; } //! Tests if \a res is an allocated resource value static bool is_allocated(HANDLE res) noexcept { return res != INVALID_HANDLE_VALUE && res != (HANDLE)NULL; } }; ``` -------------------------------- ### Capturing Variables in Boost.ScopeExit and Boost.Scope Source: https://www.boost.org/doc/libs/latest/libs/scope/doc/html/scope/scope_guards Illustrates how to capture variables by value and reference for scope exit blocks in Boost.ScopeExit and Boost.Scope. Boost.ScopeExit uses macros, while Boost.Scope leverages C++ lambda captures. ```C++ int x; std::string str; BOOST_SCOPE_EXIT(x, &str) { std::cout << "x = " << x << ", str = " << str << std::endl; } BOOST_SCOPE_EXIT_END; ``` ```C++ int x; std::string str; boost::scope::scope_exit guard([x, &str] { std::cout << "x = " << x << ", str = " << str << std::endl; }); ``` ```C++ int x; std::string str; BOOST_SCOPE_DEFER [x, &str] { std::cout << "x = " << x << ", str = " << str << std::endl; }; ``` -------------------------------- ### Simplify Handle Traits with unallocated_resource Source: https://www.boost.org/doc/libs/latest/libs/scope/doc/html/scope/unique_resource Shows how to use `boost::scope::unallocated_resource` to simplify the definition of resource traits for Windows handles by specifying unallocated values directly as template parameters. This requires C++17 support for non-type template parameters. ```C++ using handle_traits = boost::scope::unallocated_resource< INVALID_HANDLE_VALUE, (HANDLE)NULL >; ``` -------------------------------- ### Boost.Scope: Default Exception Checking with scope_fail Source: https://www.boost.org/doc/libs/latest/libs/scope/doc/html/scope/scope_guards Illustrates the use of `boost::scope::scope_fail` which, by default, checks for exceptions and executes its action block if an exception has been thrown. This provides a concise way to handle exception scenarios. ```cpp boost::scope::scope_fail guard([] { std::cout << "Exception thrown!" << std::endl; }); ``` -------------------------------- ### Include Boost Scope Exception and Error Code Checkers Source: https://www.boost.org/doc/libs/latest/libs/scope/doc/html/scope/scope_guards Headers for including Boost.Scope's built-in condition checker implementations. exception_checker detects uncaught exceptions to determine failure conditions, while error_code_checker works with error codes. ```cpp #include #include ``` -------------------------------- ### Swap unique_resource with Boost.Scope Source: https://www.boost.org/doc/libs/latest/libs/scope/doc/html/scope/unique_resource Demonstrates swapping two unique_resource objects using both member function and non-member function (via ADL) approaches. Both methods are supported by Boost.Scope when resource and deleter types support non-throwing swap, providing strong exception guarantees. ```cpp boost::scope::unique_resource< int, boost::scope::fd_deleter, boost::scope::fd_resource_traits > fd1, fd2; fd1.swap(fd2); swap(fd1, fd2); // found via ADL ``` -------------------------------- ### Boost.Scope scope_success Definition Source: https://www.boost.org/doc/libs/latest/libs/scope/doc/html/reference Defines the `scope_success` template and helper functions (`make_scope_success`). This utility executes a function only if the scope is exited without any failure or exception. Defined in . ```cpp namespace boost { namespace scope { template class scope_success; template scope_success< typename std::decay< F >::type > make_scope_success(F &&, bool = true); template scope_success< typename std::decay< F >::type, typename std::decay< C >::type > make_scope_success(F &&, C &&, bool = true); } } ``` -------------------------------- ### Move-construct scope_success (C++) Source: https://www.boost.org/doc/libs/latest/libs/scope/doc/html/doxygen/reference/classboost_1_1scope_1_1scope__success Move-constructs a scope guard from another scope_success object. Requires that the stored function and condition types are nothrow move or copy constructible. If construction throws and the source guard was active, it attempts to invoke the condition and action from the source. Marks the source guard as inactive upon successful construction. Throws only if the move construction of stored objects fails. ```cpp scope_success(scope_success && that); ``` -------------------------------- ### Construct scope_exit with Action and Condition Functions (C++) Source: https://www.boost.org/doc/libs/latest/libs/scope/doc/html/doxygen/reference/classboost_1_1scope_1_1scope__exit Constructs a scope guard with both an action function and a condition function. The construction attempts to use perfect forwarding for efficiency. If construction of either function object throws and the guard is active, the condition is checked and the action is invoked if the condition is met before propagating the exception. ```cpp template explicit scope_exit(F && func, C && cond, bool active = true); ``` -------------------------------- ### Swap Unique Resources with Friend Function Source: https://www.boost.org/doc/libs/latest/libs/scope/doc/html/doxygen/reference/classboost_1_1scope_1_1unique__resource Friend function that swaps two unique_resource instances by delegating to the member swap() function. Provides a standard swap interface compatible with std::swap and other swap-based algorithms. ```C++ void swap(unique_resource & left, unique_resource & right); ``` -------------------------------- ### defer_guard Constructor with Perfect Forwarding Source: https://www.boost.org/doc/libs/latest/libs/scope/doc/html/doxygen/reference/classboost_1_1scope_1_1defer__guard The templated constructor accepts any callable function object via perfect forwarding (F&&). It constructs the internal Func object, with special handling for nothrow constructibility. If construction fails, the provided function is invoked before propagating the exception. ```cpp template defer_guard(F && func); ``` -------------------------------- ### Boost.Scope fd_resource_traits Definition Source: https://www.boost.org/doc/libs/latest/libs/scope/doc/html/reference Defines the `fd_resource_traits` struct, providing compatibility traits for POSIX-like file descriptors with the `unique_resource` template. Located in . ```cpp namespace boost { namespace scope { struct fd_resource_traits; } } ``` -------------------------------- ### Scope Defer with Anonymous Guard - C++17 Source: https://www.boost.org/doc/libs/latest/libs/scope/doc/html/index Illustrates using BOOST_SCOPE_DEFER macro for anonymous scope guards in C++17. The guard automatically executes cleanup code when leaving scope, providing a more concise syntax compared to explicit make_scope_exit() calls. ```cpp class adder { int x, y; public: // Computes a sum of integers int compute() { // Reset variables on return or exception. // Anonymous scope guard. BOOST_SCOPE_DEFER [this] { x = 0; y = 0; }; long long int sum = static_cast< long long int >(x) + static_cast< long long int >(y); if (sum < std::numeric_limits< int >::min() || sum > std::numeric_limits< int >::max()) { throw std::overflow_error("Integer overflow"); } return static_cast< int >(sum); } }; ``` -------------------------------- ### Capturing All Variables in Boost.ScopeExit and Boost.Scope Source: https://www.boost.org/doc/libs/latest/libs/scope/doc/html/scope/scope_guards Shows how to capture all variables within the current scope for scope exit actions. Boost.ScopeExit uses `BOOST_SCOPE_EXIT_ALL`, while Boost.Scope uses lambda captures. ```C++ int x; std::string str; BOOST_SCOPE_EXIT_ALL(&) { std::cout << "x = " << x << ", str = " << str << std::endl; }; ``` ```C++ int x; std::string str; boost::scope::scope_exit guard([&] { std::cout << "x = " << x << ", str = " << str << std::endl; }); ``` ```C++ int x; std::string str; BOOST_SCOPE_DEFER [&] { std::cout << "x = " << x << ", str = " << str << std::endl; }; ``` -------------------------------- ### Create Error Code Checker Predicate (C++) Source: https://www.boost.org/doc/libs/latest/libs/scope/doc/html/doxygen/reference/error__code__checker_8hpp_1ab8a815ec04a8603fed78745d50382e87 Creates a predicate for checking whether an exception is being thrown. This function is part of the Boost scope library and requires the header. It takes an error code reference as input and returns an error_code_checker object. ```cpp // In header: template error_code_checker< ErrorCode > check_error_code(ErrorCode & ec); ``` -------------------------------- ### Boost.Scope defer_guard Definition Source: https://www.boost.org/doc/libs/latest/libs/scope/doc/html/reference Defines the `defer_guard` template used for executing a function when the scope is exited. It is part of the header. ```cpp namespace boost { namespace scope { template class defer_guard; } } ``` -------------------------------- ### Initialize unique_resource with default_resource Placeholder Source: https://www.boost.org/doc/libs/latest/libs/scope/doc/html/scope/unique_resource Illustrates the use of boost::scope::default_resource keyword to omit the resource value while specifying the deleter in unique_resource constructor arguments. The resource is value-initialized but remains in an unallocated state. This pattern is useful when you need to specify a custom deleter but don't have an initial resource value. ```cpp // Creates an unallocated unique_resource with the specified deleter boost::scope::unique_resource< int, int (*)(int) > fd(boost::scope::default_resource, &close); ``` -------------------------------- ### Boost Scope unallocated_resource::make_default() Function Source: https://www.boost.org/doc/libs/latest/libs/scope/doc/html/doxygen/reference/structboost_1_1scope_1_1unallocated__resource This C++ code snippet demonstrates the `make_default()` static function of the `boost::scope::unallocated_resource` struct template. It returns the default unallocated resource value as defined by the `DefaultValue` template parameter. This function is marked as `noexcept`. ```cpp static decltype(DefaultValue) make_default() noexcept; ``` -------------------------------- ### C++ Unconditional Scope Guard: boost::scope::defer_guard Class Source: https://www.boost.org/doc/libs/latest/libs/scope/doc/html/scope/scope_guards Shows how to directly instantiate the boost::scope::defer_guard class for unconditional scope guarding. This approach is compatible with C++11 but is less concise than the BOOST_SCOPE_DEFER macro. The guard executes an action when the scope it is defined in is exited. ```cpp #include #include // ... boost::scope::defer_guard guard{[] { std::cout << "Hello world!" << std::endl; }}; ``` -------------------------------- ### Check Resource Allocation Status with allocated() Method Source: https://www.boost.org/doc/libs/latest/libs/scope/doc/html/scope/unique_resource Shows how to use the allocated() method and contextual bool conversion operator to test whether a resource in unique_resource is in an allocated state. The method returns false for unallocated resources and true for allocated ones. The contextual bool conversion does not test the resource value itself, only the allocation status. ```cpp boost::scope::unique_resource< int, int (*)(int), boost::scope::fd_resource_traits > fd(-1, &close); assert(!fd.allocated()); assert(!fd); fd.reset(10); assert(fd.allocated()); assert(!!fd); ``` -------------------------------- ### Boost Scope unallocated_resource Struct Template Synopsis Source: https://www.boost.org/doc/libs/latest/libs/scope/doc/html/doxygen/reference/structboost_1_1scope_1_1unallocated__resource This C++ code snippet shows the synopsis for the `boost::scope::unallocated_resource` struct template. It is used to define resource traits for `unique_resource`, specifying default and optional unallocated resource values. This header is required: ``. ```cpp // In header: template struct unallocated_resource { // public static functions static decltype(DefaultValue) make_default() noexcept; template static bool is_allocated(Resource const &) noexcept; }; ``` -------------------------------- ### Boost.Scope scope_fail Definition Source: https://www.boost.org/doc/libs/latest/libs/scope/doc/html/reference Defines the `scope_fail` template and helper functions (`make_scope_fail`). This mechanism executes a function if the scope is exited due to an exception or failure condition. Defined in . ```cpp namespace boost { namespace scope { template class scope_fail; template scope_fail< typename std::decay< F >::type > make_scope_fail(F &&, bool = true); template scope_fail< typename std::decay< F >::type, typename std::decay< C >::type > make_scope_fail(F &&, C &&, bool = true); } } ``` -------------------------------- ### Boost scope::default_resource_t Struct Definition Source: https://www.boost.org/doc/libs/latest/libs/scope/doc/html/doxygen/reference/structboost_1_1scope_1_1default__resource__t Defines the `default_resource_t` struct, a placeholder type used within Boost's scope management utilities. It is declared in the `` header and serves as a default resource indicator. ```cpp // In header: struct default_resource_t { }; ``` -------------------------------- ### Boost.ScopeExit: Deferred Execution with Lambda Capture Source: https://www.boost.org/doc/libs/latest/libs/scope/doc/html/scope/scope_guards Demonstrates deferred execution using BOOST_SCOPE_DEFER with C++11 lambda capture. The captured arguments are printed within the deferred block. This approach relies on C++11 lambda features. ```cpp template< typename... Args > void foo(Args&&... args) { BOOST_SCOPE_DEFER [&args...] { std::cout << "Params: " << boost::tuples::tie(args...) << std::endl; }; } ``` -------------------------------- ### Boost.Scope: Error Code Checking with scope_fail Source: https://www.boost.org/doc/libs/latest/libs/scope/doc/html/scope/scope_guards Demonstrates using `boost::scope::scope_fail` with a custom error code checker. The action block is executed if the provided `std::error_code` object indicates an error. ```cpp std::error_code ec; boost::scope::scope_fail guard([] { std::cout << "Execution failed!" << std::endl; }, boost::scope::check_error_code(ec)); ``` -------------------------------- ### scope_fail with Default Exception Checker Source: https://www.boost.org/doc/libs/latest/libs/scope/doc/html/scope/scope_guards Demonstrates using scope_fail with default exception_checker condition. The action (vec1.pop_back) executes only if an exception occurs during the scope, providing automatic rollback on failure. ```cpp void push_back(int x, std::vector< int >& vec1, std::vector< int >& vec2) { vec1.push_back(x); // Revert vec1 modification on failure boost::scope::scope_fail rollback_guard{[&] { vec1.pop_back(); }}; vec2.push_back(x); } ```