C++核心准则C.150:unique_ptr管理的对象要用make_unique()​构建

网友投稿 539 2022-10-25

C++核心准则C.150:unique_ptr管理的对象要用make_unique()​构建

C++核心准则C.150:unique_ptr管理的对象要用make_unique()​构建

C.150: Use make_unique() to construct objects owned by unique_ptrs

C.150:unique_ptr管理的对象要用make_unique()构建

Reason(原因)

make_unique gives a more concise statement of the construction. It also ensures exception safety in complex expressions.

make_unique提供了更简洁的构建语句。在复杂的表达式中,它也可以保证异常安全。

Example(示例)

unique_ptr p {new Foo{7}}; // OK: but repetitiveauto q = make_unique(7); // Better: no repetition of Foo// Not exception-safe: the compiler may interleave the computations of //arguments as follows://// 1. allocate memory for Foo,// 2. construct Foo,// 3. call bar,// 4. construct unique_ptr.//// If bar throws, Foo will not be destroyed, and the memory-allocated //for it will leak.f(unique_ptr(new Foo()), bar());// Exception-safe: calls to functions are never interleaved.f(make_unique(), bar());

Enforcement(实施建议)

Flag the repetitive usage of template specialization list 提示重复使用模板初始化列表的代码。Flag variables declared to be unique_ptr提示使用unique_ptr定义变量的情况。

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Laravel 框架前后端模块化开发实践
下一篇:015 Python 的输入输出和字符串格式化(终于可以和计算机交流了)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~