Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Doesn't using C++ RAII eliminate some of that? Or you use raw pointers often?


Anything in C++ generally comes with its very own footgun.

The one for RAII looks like this:

  {
    mutex_guard(some_mutex);
    foo();
  }
What does this do? It locks some_mutex, then immediately unlocks it, then calls foo().


I don't understand the example. Why would it do that and not unlock after foo()?


The following code would do the right thing; see if you can spot the difference, and think about whether you would catch that in code review (g++/clang++/visualc++ won't warn about it).

  {
    mutex_guard guard(some_mutex);
    foo();
  }


Ah, now I see it and it makes sense.

The answer to the code review question is obvious. I didn't see the error even though I was told what happens.


I guess you meant std::lock_guard.

Anyway, the first example creates a temporary object which doesn't lock anything since it will be destroyed right away because it's an rvalue (not sure why would anyone do that for locking, unless not knowingly). The second example creates a proper guard which lives until the end of the scope.


Rust uses RAII too. But borrowing makes it much more powerful.


Yeah, Rust controls much more than C++ RAII does.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: