且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我应该避免哪些 C++ 陷阱?

更新时间:2023-11-10 12:57:28

一个简短的列表可能是:

A short list might be:

  • 通过使用共享指针来管理内存分配和清理来避免内存泄漏
  • 使用资源获取即初始化 (RAII) 习惯用法来管理资源清理 - 特别是在存在异常
  • 避免在构造函数中调用虚函数
  • 尽可能采用极简编码技术 - 例如,仅在需要时声明变量、范围变量以及尽可能提前设计.
  • 真正理解代码中的异常处理——包括你抛出的异常,以及你可能间接使用的类抛出的异常.这在存在模板的情况下尤为重要.
  • Avoid memory leaks through use shared pointers to manage memory allocation and cleanup
  • Use the Resource Acquisition Is Initialization (RAII) idiom to manage resource cleanup - especially in the presence of exceptions
  • Avoid calling virtual functions in constructors
  • Employ minimalist coding techniques where possible - for example, declaring variables only when needed, scoping variables, and early-out design where possible.
  • Truly understand the exception handling in your code - both with regard to exceptions you throw, as well as ones thrown by classes you may be using indirectly. This is especially important in the presence of templates.

RAII、共享指针和极简编码当然不是 C++ 特有的,但它们有助于避免在使用该语言进行开发时经常出现的问题.

RAII, shared pointers and minimalist coding are of course not specific to C++, but they help avoid problems that do frequently crop up when developing in the language.

关于这个主题的一些优秀书籍是:

Some excellent books on this subject are:

  • 有效的 C++ - Scott Meyers
  • 更有效的 C++ - Scott Meyers
  • C++ 编码标准 - Sutter &亚历山德列斯库
  • C++ 常见问题 - Cline

阅读这些书对我避免了您所问的那种陷阱的帮助比其他任何事情都大.

Reading these books has helped me more than anything else to avoid the kind of pitfalls you are asking about.