C++14新特性:deprecated的含义与使用?

一、小序

学习java或者python的同学可能都知道deprecated这个词,搞C++的同学可能对这个词还比较陌生,毕竟这个词直到C++14才出现,并且使用的频率可能也不是很高。下面一块来看一下deprecated这个词的神秘面纱。

二、含义

直译这个词的意思是“不赞成、不建议、强烈反对”,在java或者python中可以在这个词前面加上@即@deprecated表示注解,C++中的功能也类似,用来表示一个名字或者实体不再推荐使用或者已经弃用,通常已经有了更好的方法来代替这个名字或者实体,只不过为了兼容之前的老代码可能还要保留原来这个名字或者实体,但目前C++官方文档并不鼓励使用此属性。

三、使用方法

1、语法

在C++中deprecated有两种语法格式,一种不需要加字符字面值,一种需要加字符字面值,形式如下:
[[deprecated]]
[[deprecated(字符字面值)]]

2、使用

deprecated在C++中的使用范围很广泛,大部分时候我们可能只在函数前使用,以下是摘自官方的使用范围,我们最常用的可能就是在函数上使用。

1》class/struct/union: struct [[deprecated]] S;,
2》typedef-name, including those declared by alias declaration: [[deprecated]] typedef S* PS;,
using PS [[deprecated]] = S*;,
3》variable, including static data member: [[deprecated]] int x;,
4》non-static data member: union U { [[deprecated]] int n; };,
5》function: [[deprecated]] void f();,
6》namespace: namespace [[deprecated]] NS { int x; }
7》enumeration: enum [[deprecated]] E {};,
8》enumerator: enum { A [[deprecated]], B [[deprecated]] = 42 };.
9》template specialization: template<> struct [[deprecated]] X {};

原创不易,点赞鼓励一下吧!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章