当前位置: 首页 > news >正文

CANN/hixl C++通用编码规范

CANN C++ General Coding Specifications

【免费下载链接】hixlHIXL(Huawei Xfer Library)是一个灵活、高效的昇腾单边通信库,面向集群场景提供简单、可靠、高效的点对点数据传输能力。项目地址: https://gitcode.com/cann/hixl

Applicable Scope: The general programming specifications apply to all C++ code.

Rule List

Rule No.Rule NameCategory
1.1Validate external data legitimacyCode Design
1.2Prefer return values for function resultsCode Design
1.3Remove invalid and redundant codeCode Design
2.1Use new standard C++ headersHeaders
2.2Circular header dependency is prohibitedHeaders
2.3Do not include unused headersHeaders
2.4Do not reference external interfaces via extern declarationsHeaders
2.5Do not include headers within extern "C"Headers
2.6Do not use using to import namespaces in headersHeaders
3.1Avoid abusing typedef/#define type aliasesData Types
3.2Use using instead of typedef to define aliasesData Types
4.1Do not use macros to represent constantsConstants
4.2Do not use magic numbers/stringsConstants
4.3Each constant should have a single responsibilityConstants
5.1Prefer namespaces to manage global constantsVariables
5.2Avoid global variables; use singletons with cautionVariables
5.3Do not reference a variable again within its own increment/decrement expressionVariables
5.4Assign a new value to a pointer after releasing the resourceVariables
5.5Do not use uninitialized variablesVariables
6.1Variable on the left, constant on the right in comparisonsExpressions
6.2Use parentheses to clarify operator precedenceExpressions
7.1Use C++ casts instead of C-style castsCasting
8.1switch statements must have a default branchControl Statements
9.1Do not use memcpy_s/memset_s to initialize non-POD objectsDeclaration & Initialization
10.1Do not hold the pointer returned by c_str()Pointers & Arrays
10.2Prefer unique_ptr over shared_ptrPointers & Arrays
10.3Use make_shared instead of new to create shared_ptrPointers & Arrays
10.4Use smart pointers to manage objectsPointers & Arrays
10.5Do not use auto_ptrPointers & Arrays
10.6Use const for pointer/reference parameters that are not modifiedPointers & Arrays
10.7Array parameters must be passed together with their lengthPointers & Arrays
11.1Ensure string storage has a '\0' terminatorStrings
12.1Assertions must not be used for runtime error handlingAssertions
13.1Use delete/delete[] in matching pairsClasses & Objects
13.2Do not use std::move on const objectsClasses & Objects
13.3Strictly use virtual/override/finalClasses & Objects
14.1Use RAII to track dynamic allocationsFunction Design
14.2Non-local lambdas should avoid capture by referenceFunction Design
14.3Virtual functions must not use default parameter valuesFunction Design
14.4Use strongly-typed parameters; avoid void*Function Design
15.1Input parameters first, output parameters lastFunction Usage
15.2Use const T& for input, T* for outputFunction Usage
15.3Use T* or const T& when ownership is not involvedFunction Usage
15.4Use shared_ptr + move to transfer ownershipFunction Usage
15.5Single-argument constructors must use explicitFunction Usage
15.6Copy constructor and assignment operator must appear in pairsFunction Usage
15.7Do not store or delete pointer parametersFunction Usage

1. Code Design

Rule 1.1 Validate all external data for legitimacy, including but not limited to: function parameters, external input command lines, files, environment variables, user data, etc.
Rule 1.2 Prefer return values to pass function execution results; avoid using output parameters
FooBar *Func(const std::string &in);
Rule 1.3 Remove invalid, redundant, or never-executed code

Although most modern compilers can warn about invalid or never-executed code in many cases, you should respond to warnings by identifying and clearing them; you should proactively identify invalid statements or expressions and remove them from the code.

Rule 1.4 Supplementary specifications for the C++ exception mechanism
Rule 1.4.1 Specify the exception type to catch; do not catch all exceptions
// Incorrect example try { // do something; } catch (...) { // do something; } // Correct example try { // do something; } catch (const std::bad_alloc &e) { // do something; }

2. Headers and Preprocessing

Rule 2.1 Use new standard C++ headers
// Correct example #include <cstdlib> // Incorrect example #include <stdlib.h>
Rule 2.2 Circular header dependency is prohibited

Circular header dependency means that a.h includes b.h, b.h includes c.h, and c.h includes a.h, which causes any modification to any one header file to trigger recompilation of all code that includes a.h/b.h/c.h. Circular header dependency directly reflects unreasonable architectural design and can be avoided by optimizing the architecture.

Rule 2.3 Do not include headers that are not used
Rule 2.4 Do not reference external function interfaces or variables through extern declarations
Rule 2.5 Do not include headers within extern "C"
Rule 2.6 Do not use using to import namespaces in header files or before #include

3. Data Types

Recommendation 3.1 Avoid abusing typedef or #define to alias basic types
Rule 3.2 Use using instead of typedef to define type aliases to avoid shotgun modifications caused by type changes
// Correct example using FooBarPtr = std::shared_ptr<FooBar>; // Incorrect example typedef std::shared_ptr<FooBar> FooBarPtr;

4. Constants

Rule 4.1 Do not use macros to represent constants
Rule 4.2 Do not use magic numbers\strings
Recommendation 4.3 Each constant should have a single responsibility

5. Variables

Rule 5.1 Prefer namespaces to manage global constants. If there is a direct relationship with a class, static member constants may be used
namespace foo { int kGlobalVar; class Bar { private: static int static_member_var_; }; }
Rule 5.2 Avoid using global variables; use the singleton pattern with caution and avoid abuse
Rule 5.3 Do not reference a variable again within an expression that contains its own increment or decrement operation
Rule 5.4 Pointer variables pointing to resource handles or descriptors must be assigned a new value or set to NULL immediately after the resource is released
Rule 5.5 Do not use uninitialized variables

6. Expressions

Recommendation 6.1 Comparisons in expressions should follow the principle that the left side tends to change and the right side tends to remain constant
// Correct example if (ret != SUCCESS) { ... } // Incorrect example if (SUCCESS != ret) { ... }
Rule 6.2 Use parentheses to clarify operator precedence and avoid low-level errors
// Correct example if (cond1 || (cond2 && cond3)) { ... } // Incorrect example if (cond1 || cond2 && cond3) { ... }

7. Casting

Rule 7.1 Use the type casts provided by C++ instead of C-style casts; avoid using const_cast and reinterpret_cast

8. Control Statements

Rule 8.1 switch statements must have a default branch

9. Declaration and Initialization

Rule 9.1 Do not usememcpy_sormemset_sto initialize non-POD objects

10. Pointers and Arrays

Rule 10.1 Do not hold the pointer returned by std::string's c_str()
// Incorrect example const char * a = std::to_string(12345).c_str();
Rule 10.2 Prefer unique_ptr over shared_ptr
Rule 10.3 Use std::make_shared instead of new to create shared_ptr
// Correct example std::shared_ptr<FooBar> foo = std::make_shared<FooBar>(); // Incorrect example std::shared_ptr<FooBar> foo(new FooBar());
Rule 10.4 Use smart pointers to manage objects; avoid using new/delete
Rule 10.5 Do not use auto_ptr
Rule 10.6 For pointer and reference parameters, if they do not need to be modified, const must be used
Rule 10.7 When an array is used as a function parameter, its length must also be passed as a function parameter
int ParseMsg(BYTE *msg, size_t msgLen) { ... }

11. Strings

Rule 11.1 When performing storage operations on strings, ensure the string has a '\0' terminator

12. Assertions

Rule 12.1 Assertions must not be used to check errors that may occur during runtime; such runtime errors must be handled with error-handling code

13. Classes and Objects

Rule 13.1 Use delete to release a single object; use delete[] to release an array object
const int kSize = 5; int *number_array = new int[kSize]; int *number = new int(); ... delete[] number_array; number_array = nullptr; delete number; number = nullptr;
Rule 13.2 Do not use std::move on const objects
Rule 13.3 Strictly use virtual/override/final to modify virtual functions
class Base { public: virtual void Func(); }; class Derived : public Base { public: void Func() override; }; class FinalDerived : public Derived { public: void Func() final; };

14. Function Design

Rule 14.1 Use RAII to help track dynamic allocations
// Correct example { std::lock_guard<std::mutex> lock(mutex_); ... }
Rule 14.2 When using lambdas in a non-local scope, avoid capture by reference
{ int local_var = 1; auto func = [&]() { ...; std::cout << local_var << std::endl; }; thread_pool.commit(func); }
Rule 14.3 Virtual functions must not use default parameter values
Recommendation 14.4 Use strongly-typed parameters\member variables; avoid using void*

15. Function Usage

Rule 15.1 When passing function parameters, input parameters must come first, output parameters last
bool Func(const std::string &in, FooBar *out1, FooBar *out2);
Rule 15.2 When passing function parameters, useconst T &for input andT *for output
bool Func(const std::string &in, FooBar *out1, FooBar *out2);
Rule 15.3 When passing function parameters in scenarios that do not involve ownership, use T * or const T & as parameters instead of smart pointers
// Correct example bool Func(const FooBar &in); // Incorrect example bool Func(std::shared_ptr<FooBar> in);
Rule 15.4 When passing function parameters, if ownership needs to be transferred, it is recommended to use shared_ptr + move
class Foo { public: explicit Foo(shared_ptr<T> x):x_(std::move(x)){} private: shared_ptr<T> x_; };
Rule 15.5 Single-argument constructors must use explicit; multi-argument constructors must not use explicit
explicit Foo(int x); // good explicit Foo(int x, int y=0); // good Foo(int x, int y=0); // bad explicit Foo(int x, int y); // bad
Rule 15.6 Copy constructors and copy assignment operators should appear in pairs or be prohibited
class Foo { private: Foo(const Foo&) = default; Foo& operator=(const Foo&) = default; Foo(Foo&&) = delete; Foo& operator=(Foo&&) = delete; };
Rule 15.7 Do not store or delete pointer parameters

Note: For security-related coding specifications (such as memory safety, input validation, and secure function usage), see cpp-secure.md.

【免费下载链接】hixlHIXL(Huawei Xfer Library)是一个灵活、高效的昇腾单边通信库,面向集群场景提供简单、可靠、高效的点对点数据传输能力。项目地址: https://gitcode.com/cann/hixl

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

http://www.cnnetsun.cn/news/3270813.html

相关文章:

  • 2026 年 7 月 AI 模型价格战全解析:五大供应商价格、性能、选型指南
  • PIC18LF27K40驱动CMT-8540S-SMT蜂鸣器的智能硬件声音方案
  • PHP The Right Way设计模式实战:如何在PHP中正确应用23种经典设计模式
  • virtual-scroller架构设计:理解虚拟化渲染的核心机制
  • STM32与PAM8904实现高效音频驱动方案
  • 理解Meta-Llama-3.1-8B-Instruct-FP8-KV的许可证:AMD修改版权与使用限制说明
  • virtual-scroller可访问性设计:确保虚拟化内容的无障碍体验
  • 从零开始:如何快速使用Omni-Dreams-Models构建你的第一个AI应用
  • LLMDet-Swin-Tiny-HF论文精读:从arxiv到CVPR,看大语言模型如何革新目标检测
  • 3步解锁微信网页版:免安装浏览器插件让工作沟通零障碍
  • NVIDIA GLM-5-NVFP4 vs 原始GLM-5:量化模型在精度与效率上的平衡艺术
  • 网盘直链下载助手:告别限速困扰,九大平台一键获取真实下载链接
  • 如何利用Omni-Dreams-Models优化你的AI工作流程:3个实用技巧
  • Nemotron-Labs-Diffusion-3B模型配置详解:从参数设置到性能调优
  • Cloudflare:构建漏洞管理框架,将大语言模型噪声转化为全舰队防御引擎!
  • Krea 2 Identity Edit:革命性指令式图像编辑工具,一键保留人物特征的终极指南
  • PixVerse Team Ultra团队方案:AI视频生成协作与商业化指南
  • ADS127L11与PIC18F86K22高精度数据采集方案
  • OptiScaler:打破显卡壁垒的终极超采样工具,让所有游戏享受顶级画质优化
  • LLMDet-Swin-Tiny-HF震撼发布:CVPR2025 Highlight开源模型的终极目标检测指南
  • Qbot实战:三步构建本地AI自动量化交易系统的深度指南
  • 检索式语音转换技术革命:RVC框架如何用10分钟数据实现专业级AI语音合成
  • EndNote GB7714-87 会议文献格式修正:2种模板代码与3步配置流程
  • 如何快速掌握iOS位置模拟:小白也能懂的完整指南
  • MAX77654与dsPIC33FJ256GP710A电源管理方案设计
  • 数字记忆的守护者:WeChatMsg如何重塑个人数据主权
  • 锂电池组电压平衡方案:BQ25887与MK51DN512协同设计
  • STM32与MCP3202实现锂离子电池组电压平衡系统设计
  • Cesium for Unreal Token报错全解析:从认证原理到网络问题解决
  • TB6593FNG与TM4C1294NCPDT直流电机控制方案详解