本系列是开源书C++ Best Practises的中文版,全书从工具、代码格调、安全性、可维护性、可移植性、多线程、性能、正确性等角度全面介绍了古代C++我的项目的最佳实际。本文是该系列的第二篇。
代码格调
代码格调最重要的是一致性,其次是遵循C++程序员习惯的浏览格调。
C++容许任意长度的标识符名称,因而在命名时没必要非要放弃简洁,倡议应用描述性名称,并在格调上保持一致。
CamelCase
(驼峰命名法)snake_case
(蛇形命名法)
这两种是很常见的命名标准,snake_case
的长处是,在须要的时候能够适配拼写查看器。
建设代码格调指南
无论建设什么样的代码格调指南,肯定要实现指定冀望格调的.clang-format
文件。尽管这对命名没有帮忙,但对于开源我的项目来说,保持一致的格调尤为重要。
许多IDE、编辑器都反对内置的clang-format,或者能够很不便的通过加载项装置。
- VSCode: Microsoft C/C++ extension for VS Code
- CLion: [ClangFormat as alternative formatter
](https://www.jetbrains.com/help/clion/clangformat-as-alternati...) - VisualStudio: ClangFormat
- Resharper++: Using Clang-Format
Vim
- Format your C family code
- vim-autoformat
- XCode: ClangFormat-Xcode
通用C++命名约定
- 类以大写字母结尾:
MyClass
。 - 函数和变量以小写字母结尾:
myMethod
。 - 常量全副大写:
const double PI=3.14159265358979323
。
C++规范库(以及其余驰名C++库,如Boost)应用以下领导准则:
- 宏应用大写和下划线:
INT_MAX
。 - 模板参数名应用驼峰命名法:
InputIterator
。 - 所有其余名称都应用蛇形命名法:
unordered_map
。
辨别公有对象数据
应用m_
前缀命名公有数据,以区别于公共数据,m_
代表“member(成员)”数据。
辨别函数参数
最重要的是放弃代码库的一致性,这是一种有助于放弃一致性的形式。
应用t_
前缀命名函数参数,t_
能够被认为是“the”,但其能够示意任意含意,要害是要将函数参数与作用域内的其余变量辨别开来,同时遵循统一的命名策略。
能够为团队抉择任何前缀或后缀,上面是一个例子,提出了一个有争议的倡议,相干探讨见issue #11。
struct Size{ int width; int height; Size(int t_width, int t_height) : width(t_width), height(t_height) {}};// This version might make sense for thread safety or something,// but more to the point, sometimes we need to hide data, sometimes we don't.class PrivateSize{ public: int width() const { return m_width; } int height() const { return m_height; } PrivateSize(int t_width, int t_height) : m_width(t_width), m_height(t_height) {} private: int m_width; int m_height;};
不要用下划线(\_)作为名字的结尾
\_ 结尾的名字有可能与编译器或规范库的保留名发生冲突: What are the rules about using an underscore in a C++ identifier?
良好代码格调示例
class MyClass{public: MyClass(int t_data) : m_data(t_data) { } int getData() const { return m_data; }private: int m_data;};
使Out-of-Source-Directory构建
确保构建生成的文件寄存在与源文件夹拆散的输入文件夹中。
应用nullptr
C++11引入了nullptr
示意空指针,应该用来代替0
或NULL
来批示空指针。
正文
正文块应该应用//
,而不是/* */
,应用//
能够更容易的在调试时正文掉代码块。
// this function does somethingint myFunc(){}
要在调试期间正文掉这个函数块,能够这样做:
/*// this function does somethingint myFunc(){}*/
如果函数头正文应用/* */
,这么做就会有抵触。
永远不要在头文件中应用using namespace
这会导致正在using
的命名空间被强行拉入到蕴含头文件的所有文件的命名空间中,从而造成命名空间净化,并可能在导致名称抵触。在实现文件中using
命名空间就足够了。
Include爱护符
头文件必须蕴含名称清晰的include爱护符,从而防止同一头文件被屡次include的问题,并避免与其余我的项目的头文件发生冲突。
#ifndef MYPROJECT_MYCLASS_HPP#define MYPROJECT_MYCLASS_HPPnamespace MyProject { class MyClass { };}#endif
此外还能够思考应用#pragma once
指令,这是许多编译器的准规范,内容简短,用意明确。
代码块必须蕴含{}
省略{}
可能会导致代码语义谬误。
// Bad Idea// This compiles and does what you want, but can lead to confusing// errors if modification are made in the future and close attention// is not paid.for (int i = 0; i < 15; ++i) std::cout << i << std::endl;// Bad Idea// The cout is not part of the loop in this case even though it appears to be.int sum = 0;for (int i = 0; i < 15; ++i) ++sum; std::cout << i << std::endl;// Good Idea// It's clear which statements are part of the loop (or if block, or whatever).int sum = 0;for (int i = 0; i < 15; ++i) { ++sum; std::cout << i << std::endl;}
放弃每行代码长度正当
// Bad Idea// hard to followif (x && y && myFunctionThatReturnsBool() && caseNumber3 && (15 > 12 || 2 < 3)) {}// Good Idea// Logical grouping, easier to readif (x && y && myFunctionThatReturnsBool() && caseNumber3 && (15 > 12 || 2 < 3)) {}
许多我的项目和编码标准都对此制订了软规定,即每行字符应该少于80或100个,这样的代码通常更容易浏览,此外还能够把两个文件并排显示在一个屏幕上,不必小字体也能看到全副代码。
应用""
示意include本地文件
...<>
示意include系统文件。
// Bad Idea. Requires extra -I directives to the compiler// and goes against standards.#include <string>#include <includes/MyHeader.hpp>// Worse Idea// Requires potentially even more specific -I directives and// makes code more difficult to package and distribute.#include <string>#include <MyHeader.hpp>// Good Idea// Requires no extra params and notifies the user that the file// is a local file.#include <string>#include "MyHeader.hpp"
初始化成员变量
...应用成员初始化列表。
对于POD类型,初始化列表的性能与手动初始化雷同,但对于其余类型,有显著的性能晋升,见下文。
// Bad Ideaclass MyClass{public: MyClass(int t_value) { m_value = t_value; }private: int m_value;};// Bad Idea// This leads to an additional constructor call for m_myOtherClass// before the assignment.class MyClass{public: MyClass(MyOtherClass t_myOtherClass) { m_myOtherClass = t_myOtherClass; }private: MyOtherClass m_myOtherClass;};// Good Idea// There is no performance gain here but the code is cleaner.class MyClass{public: MyClass(int t_value) : m_value(t_value) { }private: int m_value;};// Good Idea// The default constructor for m_myOtherClass is never called here, so // there is a performance gain if MyOtherClass is not is_trivially_default_constructible. class MyClass{public: MyClass(MyOtherClass t_myOtherClass) : m_myOtherClass(t_myOtherClass) { }private: MyOtherClass m_myOtherClass;};
在C++11中,能够为每个成员初始化默认值(应用=
或应用{}
)。
应用=
设置默认值
// ... //private: int m_value = 0; // allowed unsigned m_value_2 = -1; // narrowing from signed to unsigned allowed// ... //
这样能够确保不会呈现构造函数“遗记”初始化成员对象的状况。
用大括号初始化默认值
用大括号初始化不容许在编译时截断数据长度。
// Best Idea// ... //private: int m_value{ 0 }; // allowed unsigned m_value_2 { -1 }; // narrowing from signed to unsigned not allowed, leads to a compile time error// ... //
除非有明确的理由,否则优先应用{}
初始化,而不是=
。
遗记初始化成员会导致未定义行为谬误,而这些谬误通常很难发现。
如果成员变量在初始化后不会更改,则将其标记为const
。
class MyClass{public: MyClass(int t_value) : m_value{t_value} { }private: const int m_value{0};};
因为不能给const成员变量赋值,拷贝赋值操作可能对这样的类没有意义。
总是应用命名空间
简直没有理由须要全局命名空间中申明标识符。相同,函数和类应该存在于适当命名的命名空间中,或者存在于命名空间里的类中。放在全局命名空间中的标识符有可能与来自其余库(次要是没有命名空间的C库)的标识符发生冲突。
为规范库个性应用正确的整数类型
规范库通常应用std::size_t
来解决与尺寸相干的内容,size_t
的大小由实现定义。
一般来说,应用auto
能够防止大部分问题。
请确保应用正确的整数类型,并与C++规范库保持一致,否则有可能在以后应用的平台上不会收回正告,但如果切换到其余平台,可能会收回正告。
留神,在对无符号数执行某些操作时,可能会导致整数下溢。例如:
std::vector<int> v1{2,3,4,5,6,7,8,9};std::vector<int> v2{9,8,7,6,5,4,3,2,1};const auto s1 = v1.size();const auto s2 = v2.size();const auto diff = s1 - s2; // diff underflows to a very large number
应用.hpp
和.cpp
作为文件扩展名
归根结底,这是集体爱好问题,然而.hpp和.cpp已被各种编辑器和工具宽泛认可。因而,这是一个求实的抉择。具体来说,Visual Studio只自动识别.cpp和.cxx为C++文件,而Vim不肯定会把.cc辨认为C++文件。
某个特地大的我的项目(OpenStudio)应用.hpp和.cpp示意用户生成的文件,而应用.hxx和.cxx示意工具生成的文件。两者都能被很好的辨认,并且辨别开来有很大的帮忙。
不要混用tab和空格
某些编辑器喜爱在默认状况下应用tab和空格的混合缩进,这使得没有应用完全相同的tab缩进设置的人很难浏览代码。请配置好编辑器,确保不会产生这种状况。
不要将有副作用的代码放在assert()中
assert(registerSomeThing()); // make sure that registerSomeThing() returns true
上述代码在debug模式下构建时能够胜利运行,但在进行release构建时会被编译器删除,从而造成debug和release构建的行为不统一,起因在于assert()
是一个宏,它在release模式下开展为空。
不要胆怯模板
模板能够帮忙咱们保持DRY准则。因为宏有不恪守命名空间等问题,因而能用模板的中央就不要用宏。
理智的应用操作符重载
运算符重载是为了反对表白性语法。比方让两个大数相加看起来像a + b
,而不是a.add(b)
。另一个常见的例子是std::string
,通常应用string1 + string2
连贯两个字符串。
然而,应用过多或谬误的操作符重载很容易写出可读性不强的表达式。在重载操作符时,要遵循stackoverflow文章中形容的三条根本规定。
具体来说,记住以下几点:
- 解决资源时必须重载
operator=()
,参见上面Rule of Zero章节。 - 对于所有其余操作符,通常只有在须要在上下文中应用时才重载。典型的场景是用+连贯事物,负号能够被认为是“真”或“假”的表达式,等等。
- 肯定要留神操作符优先级,尽量避免不直观的构造。
- 除非实现数字类型或遵循特定域中可辨认的语法,否则不要重载~或%这样的内部操作符。
- 永远不要重载
operator,()
(逗号操作符)。 - 解决流时应用非成员函数
operator>>()
和operator<<()
。例如,能够重载operator<<(std::ostream &, MyClass const &)
,从而容许将类“写入”到一个流中,例如std::cout
或std::fstream
或std::stringstream
,后者通常用于创立值的字符串示意。 - 这篇文章形容了更多须要重载的常见操作符: What are the basic rules and idioms for operator overloading?。
更多对于自定义操作符实现细节的技巧能够参考: C++ Operator Overloading Guidelines。
防止隐式转换
单参数构造函数
能够在编译时利用单参数构造函数在类型之间主动转换,比方像std::string(const char *)
,这样的转换很不便,但通常应该防止,因为可能会减少额定的运行时开销。
相同,能够将单参数构造函数标记为explicit
,从而要求显式调用。
转换操作符
与单参数构造函数相似,编译器能够调用转换操作符,同样也会引入额定开销,也应该被标记为explicit
。
//bad ideastruct S { operator int() { return 2; }};//good ideastruct S { explicit operator int() { return 2; }};
思考Rule of Zero
Rule of Zero规定,除非所结构的类具备某种新的所有权模式,否则不提供编译器能够提供的任何函数(拷贝构造函数、拷贝赋值操作符、挪动构造函数、挪动赋值操作符、析构函数)。
指标是让编译器提供在增加更多成员变量时主动保护的最佳版本。
这篇文章介绍了这一准则的背景,并解释了简直能够笼罩所有状况的实现技术: C++'s Rule of Zero。
你好,我是俞凡,在Motorola做过研发,当初在Mavenir做技术工作,对通信、网络、后端架构、云原生、DevOps、CICD、区块链、AI等技术始终保持着浓重的趣味,平时喜爱浏览、思考,置信继续学习、一生成长,欢送一起交流学习。 \
微信公众号:DeepNoMind
本文由mdnice多平台公布