4 ms·
It's a nit I guess but I feel like RAII is a pattern, not a feature of the language. Haven't done C++ in years but as I recall it doesn't have anything like pyt
by markbnj 9y ago
It's a nit I guess but I feel like RAII is a pattern, not a feature of the language. Haven't done C++ in years but as I recall it doesn't have anything like python's with or finally blocks, which would both serve the purpose illustrated here. Using destructors to perform things when exiting a block is fine, I guess, but it does introduce hidden behaviors that will need to be well documented.
- Too 9y agoEvery single variable in C++ is implicitly surrounded by a with-block. And __exit__ is called destructor.
- stabbles 9y agoIt's a known trick also used in the standard library of C++. For instance in multithreading { std::lock_guard<std::mutex> lock(some_mutex); ... } owns a mutex for duration of the scope. The constructor claims it, and the destructor releases it. But yeah, it has downsides. If you would not name the variable, and do `std::lock_guard<std::mutex>(some_mutex);`, then its scope is limited to a single line, and the lock is immediately released.
- masklinn 9y agoAnd to toot its horn, Rust combines that with its ownership semantics to create a very neat pattern: many locks have to do with resources yet almost all languages split the resource and the lock and you've got to know that you need to acquire one lock before you use a resource without any intrinsic relation between the two. In Rust however sync::Mutex::new takes a value, which the lock owns, and acquiring the lock yields a MutexGuard which acts as a reference to the wrapped value. You must acquire the lock to get access to the value (since it's owned by the lock itself), and once the lock is released you have no way to access the locked value (unless you created a copy). > If you would not name the variable, and do `std::lock_guard<std::mutex>(some_mutex);`, then its scope is limited to a single line, and the lock is immediately released. OTOH you can pretty trivially create a wrapper/extension which takes a lambda, acquires the lock, calls the lambda then drops the lock. It could even return the lambda's result while at it.