什么 C++习语应该 C++程序员用?
C++ 程序员应该了解哪些 C++ 习惯用法?
我所说的 C++ 习惯用法是指仅适用于 C++ 或比大多数其他语言更适用于 C++ 的设计模式或执行某些操作的方法。
为什么要使用这些习语,这些习语有什么作用?
What C++ idioms should C++ programmers know?
By C++ idioms, I mean design patterns or way of doing certain things that are only applicable for C++ or more applicable for C++ than most other languages.
Why one should use the idioms, and what do the idioms accomplish?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
到目前为止,要学习和了解(几乎)C++ 独有的最重要的“模式”是 RAII(资源获取即初始化)。
编辑:(回答编辑到问题中的额外问题)。您主要使用 RAII 来(半)自动化资源管理。最明显的用途是当拥有的对象超出范围时释放对象拥有的资源,例如释放内存或关闭文件。
By far the single most important "pattern" to learn and know that's (nearly) unique to C++ is RAII (Resource Acquisition Is Initialization).
Edit: (To answer extra question edited into the question). You use RAII primarily to (semi-)automate resource management. The most obvious use is freeing resources owned by objects when the owning objects go out of scope, such as freeing memory or closing files.
这是一个列表。如果我必须选择一个,我可能会选择奇怪的重复模板模式或虚拟构造函数。
Here is one list. If I had to pick a couple I might go with the Curiously Recurring Template Pattern or Virtual Contstructors.
PIMPL,又名 P 指向 IMPL 注释?
PIMPL, aka P ointer to IMPL ementation ?
模板元编程。它很棒,因为它基本上是编译时鸭子类型,因此您可以通过静态类型的速度获得鸭子类型的大部分灵活性。
Template metaprogramming. It's great because it's basically compile-time duck typing, so you get most of the flexibility of duck typing with the speed of static typing.
如果您想充分利用 STL,那么迭代器和函子/函数对象是必不可少的习惯用法。迭代器的使用也隐含地依赖于“半开范围”的习惯用法。
If you want to get the most out of the STL then iterators and functors/function objects are essential idioms. The use of iterators also implicitly relies on the 'half-open range' idiom too.
利用强类型和 const 正确性也非常有帮助。
我还禁止默认的复制构造函数和赋值运算符。我实际上超越了这一点,但这些是最常见的。我认为如果他们不含蓄的话生活会更容易。
Exploiting Strong Typing and
const
correctness is also extremely helpful.I also prohibit default copy constructors and assignment operators. I actually go beyond that, but those are the most common. I think life would be easier if they were not implicit.
RAII、COW、pimpl、demeter 定律(不确定是否可以归类为习语)、类型特征和策略。 (COW 和 Demeter 定律并不局限于 C++)
RAII, COW, pimpl, law of demeter (not sure if can be classified as idiom), type traits and policies. (COW and law of demeter are not limited to C++ though)