|
|
|
|
|
by questioner8216
200 days 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.
|
|
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.