C++注释风格

最近要给之前做的动力学项目加上注释, 寻思着有没有什么看起来比较优雅的注释风格, 在腾讯云社区找到一篇不错的相关文章, 特此提炼总结一下~

参考文章: C++注释风格建议

1. 文件注释示例

//
//@Copyright:Copyright 2018 Google Inc
//@License:GPL
//@Birth:created by Dablelv on 2018-08-02
//@Content:开源JSON解析库
//@Version:1.1.1
//@Revision:last revised by lvlv on 2018-09-02
//

这里提到了Copyright和License的问题, 分享一篇解释这个比较通俗易懂的文章~ 开源许可证教程

2. 类注释示例

// Iterates over the contents of a GargantuanTable.
// Example:
//    GargantuanTableIterator* iter = table->NewIterator();
//    for (iter->Seek("foo"); !iter->done(); iter->Next()) 
//    {
//      process(iter->key(), iter->value());
//    }
//    delete iter;
class GargantuanTableIterator
{
    ...
};

3. 函数声明注释示例

//
// @brief:获取容器迭代器
// @params:void
// @ret:返回容器迭代器
// @birth:created by Dablelv on 20180802
//
Iterator* getIterator() const;

4. 函数定义注释示例

// Divide result by two, taking into account that x contains the carry from the add.
for (int i = 0; i < result->size(); i++)
{
    x = (x << 8) + (*result)[i];
    (*result)[i] = x >> 1;
    x &= 1;
}

比较隐晦的地方要在行尾加入注释, 在行尾空两格或一个Tab进行注释. 比如:

mmap_budget = max(0, mmap_budget - index_->length());
if (mmap_budget >= data_size_ && !MmapData(mmap_chunk_bytes, mlock))
{
    return;  // Error already logged.
}

前后相邻几行都有注释, 可以适当调整使之可读性更好.

...
DoSomething();                  // Comment here so the comments line up.
DoSomethingElseThatIsLonger();  // Comment here so after two spaces
...

5. 类数据成员注释示例

private:
    //Used to bounds-check table accesses. -1 means that we don't yet know how many entries the table has.
    int num_total_entries_;

6. 全局变量注释示例

//The total number of tests cases that we run through in this regression test.
const int kNumTestCases = 6;

7. TODO注释示例

如果项目中存在功能代码有待修改和编写地方, 建议使用TODO注释进行简略说明. TODO注释的作用类似于书签, 便于开发者快速找到需要继续开发的位置和有待完成的功能, 起到提醒标记的作用.

TODO注释要使用全大写的字符串TODO, 在随后的圆括号里写上负责人的名字、邮件地址、bug ID或其它身份标识和与这一TODO相关的问题, 主要目的是让添加注释的人或负责人可根据规范的TODO格式进行查找. 添加TODO注释一般都是写上自己的名字, 但并不意味着一定要自己来修正, 除非自己是该TODO所描述的问题的负责人.
简单示例:

// TODO(kl@gmail.com): Use a "*" here for concatenation operator.
// TODO(Zeke): change this to use relations.
// TODO(bug 12345): remove the "Last visitors" feature

如果加TODO是为了在“将来某一天做某事”, 可以附上一个非常明确的时间“Fix by November 2005”), 或者一个明确的事项(“Remove this code when all clients can handle XML responses.”).

8. 弃用注释示例

通过弃用注释(DEPRECATED comments) 以标记某接口点已弃用. 可以写上包含全大写的DEPRECATED的注释, 以标记某接口为弃用状态.

弃用注释应当包涵简短而清晰的指引, 以帮助其他人修复其调用点. 在C++中, 你可以将一个弃用函数改造成一个内联函数, 这一函数将调用新的接口. 在DEPRECATED一词后, 在括号中留下负责人的名字、邮箱地址以及其他身份标识. 注释可以放在接口声明前, 或者同一行. 简单示例如下:

//DEPRECATED(dablelv):new interface changed to bool IsTableFull(const Table& t)
bool IsTableFull();

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注