☰
  • 首页
  • 规则分类
  • 项目介绍
search
•••

避免使用已过时的标准库组件

6.12.9 ID_obsoleteStdFunction
目录 › next › previous

已过时的标准库组件会被语言标准弃用,应改用更完善的替代方法。

下列 C++ 标准库组件已过时:

  • 类型 auto_ptr
  • 类型 binder1st、binder2nd 和函数 bind1st、bind2nd
  • 类型 const_mem_fun1_ref_t、const_mem_fun1_t、const_mem_fun_ref_t、const_mem_fun_t
  • 类型 ios_base 的成员 io_state、open_mode、seek_dir、streamoff、streampos
  • 类型 mem_fun1_ref_t、mem_fun1_t、mem_fun_ref_t、mem_fun_ref、mem_fun_t 和函数 mem_fun
  • 类型 pointer_to_binary_function、pointer_to_unary_function 和函数 ptr_fun
  • 函数 random_shuffle
  • 类型 strstream、strstreambuf、istrstream、ostrstream
  • 类型 unary_function、binary_function
  • 类型 unexpected_handler 和函数 unexpected、set_unexpected、get_unexpected

示例:

auto_ptr<T> a(new T);      // Non-compliant
auto_ptr<T> b;             // Non-compliant
void foo(auto_ptr<T> p);   // Non-compliant

b = a;    // ‘a’ is invalid after the assignment
foo(b);   // ‘b’ is invalid after the call
....      // Undefined behavior if dereference ‘a’ or ‘b’

auto_ptr 对象的赋值或传参都会引起资源所有权的转移,如 b = a 会使 a 的资源被转移到 b 中,foo(b) 会使 b 的资源转移到参数中,这种方式很容易使人误解,故 auto_ptr 被 C++11 标准判为已过时,并从 C++17 标准中移出。

可使用 unique_ptr 代替 auto_ptr:

unique_ptr<T> a = make_unique<T>();
unique_ptr<T> b;

b = a;         // Compile error
b = move(a);   // OK, explicit moving

unique_ptr 禁止资源所有权隐式转移,语义更为明确。

相关

ID_obsoleteFunction

依据

ISO/IEC 14882:2011 D.6-deprecated ISO/IEC 14882:2011 D.7-deprecated ISO/IEC 14882:2011 D.8-deprecated ISO/IEC 14882:2011 D.9-deprecated ISO/IEC 14882:2011 D.10-deprecated ISO/IEC 14882:2011 D.11-deprecated ISO/IEC 14882:2017 20.5.4.3.1(1)
Copyright©2024 360 Security Technology Inc., Licensed under the Apache-2.0 license.