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

2022-01-07 00:00:00 c++ stl

我记得第一次学习 STL 中的向量,一段时间后,我想在我的一个项目中使用 bool 向量.在看到一些奇怪的行为并做了一些研究之后,我了解到 一个向量bools 并不是真正的 bools 向量.

I remember first learning about vectors in the STL and after some time, I wanted to use a vector of bools for one of my projects. After seeing some strange behavior and doing some research, I learned that a vector of bools is not really a vector of bools.

在 C++ 中还有其他常见的陷阱需要避免吗?

Are there any other common pitfalls to avoid in C++?

推荐答案

一个简短的列表可能是:

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.

相关文章