命名空间
变体
操作

C++ 属性: deprecated (自 C++14 起)

来自 cppreference.cn
< cpp‎ | language‎ | attributes
 
 
C++ 语言
通用主题
流程控制
条件执行语句
if
迭代语句(循环)
for
range-for (C++11)
跳转语句
函数
函数声明
Lambda 函数表达式
inline 说明符
动态异常规范 (直到 C++17* 弃用)
noexcept 说明符 (C++11)
异常
命名空间
类型
说明符
const/volatile
decltype (C++11)
auto (C++11)
constexpr (C++11)
consteval (C++20)
constinit (C++20)
存储持续时间说明符
初始化
 
 
属性
(C++23)
(C++11)(直到 C++26)
deprecated
(C++14)
(C++20)
(C++17)
(C++11)
(C++20)
 

指示使用以此属性声明的名称或实体是 deprecated,即允许使用,但不建议出于某些原因使用。

目录

[编辑] 语法

[[deprecated]] (1)
[[deprecated( string-literal )]] (2)
string-literal - 一个未求值的字符串字面量,可用于解释弃用的理由和/或建议替换实体

[编辑] 解释

指示允许使用以此属性声明的名称或实体,但不建议出于某些原因使用。编译器通常会对这种使用发出警告。string-literal(如果指定)通常包含在警告中。

此属性允许在以下名称或实体的声明中使用

  • [[deprecated]] typedef S* PS;,
  • using PS [[deprecated]] = S*;,
  • (非成员)变量,例如, [[deprecated]] int x;
  • 静态数据成员,例如, struct S { [[deprecated]] static constexpr char CR{13}; };
  • 非静态数据成员,例如, union U { [[deprecated]] int n; };
  • 函数,例如, [[deprecated]] void f();
  • 命名空间,例如, namespace [[deprecated]] NS { int x; }
  • 枚举,例如, enum [[deprecated]] E {};
  • 枚举器,例如, enum { A [[deprecated]], B [[deprecated]] = 42 };
(自 C++17 起)
  • 模板特化,例如, template<> struct [[deprecated]] X<int> {};

声明为非 deprecated 的名称可以重新声明为 deprecated。声明为 deprecated 的名称不能通过重新声明而不使用此属性来取消 deprecated。

[编辑] 示例

#include <iostream>
 
[[deprecated]]
void TriassicPeriod()
{
    std::clog << "Triassic Period: [251.9 - 208.5] million years ago.\n";
}
 
[[deprecated("Use NeogenePeriod() instead.")]]
void JurassicPeriod()
{
    std::clog << "Jurassic Period: [201.3 - 152.1] million years ago.\n";
}
 
[[deprecated("Use calcSomethingDifferently(int).")]]
int calcSomething(int x)
{
    return x * 2;
}
 
int main()
{
    TriassicPeriod();
    JurassicPeriod();
}

可能的输出

Triassic Period: [251.9 - 208.5] million years ago.
Jurassic Period: [201.3 - 152.1] million years ago.
 
main.cpp:20:5: warning: 'TriassicPeriod' is deprecated [-Wdeprecated-declarations]
    TriassicPeriod();
    ^
main.cpp:3:3: note: 'TriassicPeriod' has been explicitly marked deprecated here
[[deprecated]]
  ^
main.cpp:21:5: warning: 'JurassicPeriod' is deprecated: Use NeogenePeriod() instead ⮠
 [-Wdeprecated-declarations]
    JurassicPeriod();
    ^
main.cpp:8:3: note: 'JurassicPeriod' has been explicitly marked deprecated here
[[deprecated("Use NeogenePeriod() instead")]]
  ^
2 warnings generated.

[编辑] 参考文献

  • C++23 标准 (ISO/IEC 14882:2024)
  • 9.12.5 Deprecated 属性 [dcl.attr.deprecated]
  • C++20 标准 (ISO/IEC 14882:2020)
  • 9.12.4 Deprecated 属性 [dcl.attr.deprecated]
  • C++17 标准 (ISO/IEC 14882:2017)
  • 10.6.4 Deprecated 属性 [dcl.attr.deprecated]
  • C++14 标准 (ISO/IEC 14882:2014)
  • 7.6.5 Deprecated 属性 [dcl.attr.deprecated]

[编辑] 参见

C 文档 关于 deprecated