我应该避免什么C ++陷阱? [英] What C++ pitfalls should I avoid?

查看:113
本文介绍了我应该避免什么C ++陷阱?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

简短列表可能是:




  • 通过使用共享指针管理内存分配,清除

  • 使用资源获取初始化(RAII)

  • 避免在构造函数中调用虚函数

  • 在可能的情况下使用简约编码技术 - 例如,只在需要时声明变量,在可能的情况下定义变量和早期设计。

  • 真正了解代码中的异常处理 - 包括抛出的异常,以及可能间接使用的类抛出的异常。这在存在模板时尤为重要。



RAII,共享指针和简约编码当然不是特定于C ++的,帮助避免在用语言开发时经常出现的问题。



有关此主题的一些优秀书籍是:




  • Effective C ++ - Scott Meyers

  • 更有效的C ++ - Scott Meyers

  • C ++编码标准 - Sutter& Alexandrescu

  • C ++常见问题 - Cline



阅读这些书帮助我避免你所问的那种陷阱。


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.

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

解决方案

A short list might be:

  • 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, 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:

  • Effective C++ - Scott Meyers
  • More Effective C++ - Scott Meyers
  • C++ Coding Standards - Sutter & Alexandrescu
  • C++ FAQs - Cline

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

这篇关于我应该避免什么C ++陷阱?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆