std::make_shared() change in C++17

巧了我就是萌 提交于 2019-12-03 04:25:13

The evaluation order of function arguments are changed by P0400R0.

Before the change, evaluation of function arguments are unsequenced relative to one another. This means evaluation of g() may be inserted into the evaluation of std::shared_ptr<int>(new int(42)), which causes the situation described in your quoted context.

After the change, evaluation of function arguments are indeterminately sequenced with no interleaving, which means all side effects of std::shared_ptr<int>(new int(42)) take place either before or after those of g(). Now consider the case where g() may throw.

  • If all side effects of std::shared_ptr<int>(new int(42)) take place before those of g(), the memory allocated will be deallocated by the destructor of std::shared_ptr<int>.

  • If all side effects of std::shared_ptr<int>(new int(42)) take place after those of g(), there is even no memory allocation.

In either case, there is no memory leak again anyway.

lisyarus

The P0145R3 paper (which was accepted into C++17) refines the order of evaluation of several C++ constructs, including

Postfix expressions are evaluated from left to right. This includes functions calls and member selection expressions

Specifically, the paper adds the following text to 5.2.2/4 paragraph of the standard:

The postfix-expression is sequenced before each expression in the expression-list and any default argument. Every value computation and side effect associated with the initialization of a parameter, and the initialization itself, is sequenced before every value computation and side effect associated with the initialization of any subsequent parameter.

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