News for hackers. Stuff that matters.
Re:Implementing Go's defer keyword in C++ by stabbles on Saturday October 21, 2017 @06:03PM (#15523860)
It'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.

Re:Implementing Go's defer keyword in C++ by masklinn on Sunday October 22, 2017 @06:32AM (#15526060)
And 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.