top | item 46041823

(no title)

questioner8216 | 3 months ago

I am not very familiar with C++'s API, but I believe that you are right that the C++ example in the article is incorrect, though for a different reason, namely that RAII is supported also in C++.

In C++, a class like std::lock_guard also provides "Automatic unlock". AFAICT, the article argues that only Rust's API provides that.

    {
        const std::lock_guard<std::mutex> lock(mtx);
        account.balance -= amount;
        account.transaction_count++;
    } // Automatically unlocked.

discuss

order

aw1621107|3 months ago

> In C++, a class like std::lock_guard also provides "Automatic unlock". AFAICT, the article argues that only Rust's API provides that.

The issue isn't automatic unlocking. From the article:

> The problem? Nothing stops you from accessing account without locking the mutex first. The compiler won’t catch this bug.

i.e., a C++ compiler will happily compile code that modifies `account` without taking the lock first. Your lock_guard example suffers from this same issue.

Nothing in the C++ stdlib provides an API that makes it impossible to access `account` without first taking the lock, and while you can write C++ classes that approximate the Rust API you can't quite reach the same level of robustness without external help.

questioner8216|3 months ago

That is a different topic from what I wrote about.

The article wrote:

> Automatic unlock: When you lock, you receive a guard. When the guard goes out of scope, it automatically unlocks. No manual cleanup needed.

And presented Rust as being different from C++ regarding that, and the C++ example was not idiomatic, since it did not use something like std::lock_guard.

I have not addressed the rest of your comment, since it is a different topic, sorry.