How to use lock_guard when returning protected data

前端 未结 3 733
半阙折子戏
半阙折子戏 2020-12-06 09:46

I have a question concerning the use of boost::lock_guard (or similar scoped locks) and using variables that should be protected by the lock in a return

相关标签:
3条回答
  • 2020-12-06 10:04

    How is the order of destroying local objects and copying the return value?

    Generally, stack objects are destroyed in reverse order of creation. As previously stated, both approaches you specify will provide the desired behavior.

    How does return value optimization affect this?

    RVO should not be a concern here - all this does is construct the output object directly into the stack frame buffer - avoiding the overhead of creating a named temporary object (as in your 2nd example above). This is done before local destructors are invoked.

    You're best off using the code from example 1 above.

    0 讨论(0)
  • 2020-12-06 10:27

    Just a straight return as in your first example is correct. The return value is constructed before the local variables are destroyed, and thus before the lock is released.

    0 讨论(0)
  • 2020-12-06 10:28

    Both pieces are equivalent. In fact for case #1 - C++ compiler will create structure described in case #2. So #1 is preferable.

    0 讨论(0)
提交回复
热议问题