How to use lock_guard when returning protected data

我的未来我决定 提交于 2019-11-27 23:31:14

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.

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!