Hacker News new | ask | show | jobs
by wyldfire 2329 days ago
If it's constructed as a temporary rvalue but never stored or passed as an argument, I think there's places where the compiler can elide the code entirely. Whereas you might prefer it have the system side effects associated with construction and destruction.
1 comments

So it's for copy/move-constructors only?
No. Sorry for being unclear. [1] is a great video that covers a lot of good stuff in particular this usability bug. It's worth watching in its entirety.

If you don't want to sit through the video, here's the broken code in question:

    void Obj::update() noexcept {
        unique_lock<mutex>(m_mutex);
        do_the_mutation();
    }
"unique_lock<mutex>(m_mutex);" has no effect, but you might mistakenly think that this will block on m_mutex. Labeling unique_lock's constructor as [[nodiscard]] would force you to think twice. See [2] for more details.

[1] https://youtu.be/lkgszkPnV8g?t=1767

[2] http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p177...

Ahh, that makes sense! On my phone at the moment but will check out the video too, thanks!