C++ 中模板和 STL 的缺点

发布于 2024-07-08 02:47:34 字数 1450 浏览 3 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

橘寄 2024-07-15 02:47:34

首先,如果它们可以帮助您解决问题,您应该使用它们。 模板是 C++ 非常重要的一部分,并且多年来一直是标准的一部分。 STL 在运行时非常强大且快速,应该受到所有像样的编译器的支持,但当然也存在一些问题。

  • 如果您使用的是非常旧的编译器,则可能无法完全支持 STL。
  • STL 实现的线程安全性可能适用于您的应用程序
  • 模板可能会导致编译时间变慢,并且可能导致可执行文件变大,尤其是对于较旧的编译器。
  • 编译器经常在使用模板的代码上产生难以理解的错误消息。

仅举几例,但不使用它们的缺点可能会更大。

First, you should use probably use them if they help you solve your problem. Templates are a very important part of C++ and have been part of the standard for years. STL is very powerful and fast at run time and should be supported on all decent compilers, but of course there are issues.

  • If you have a really old compiler, STL might not be completely supported.
  • The thread-safety of the STL implementation might be work for your application
  • Templates can lead to slower compile-times and possibly larger executable, especially with older compilers.
  • Compilers often produce incomprehensible error messages on code using templates.

just to name a few, but the drawbacks of not using them are likely to be much greater.

甜心小果奶 2024-07-15 02:47:34

明显的缺点:

  • 语法可能很糟糕 - C++ 中的一些模板语法确实突破了理智的极限,并且与语言的其他部分重叠(例如 >>)

  • 很多人不太了解 STL,所以你可能限制您的受众。

  • 错误消息往往极其复杂。

  • STL集合的设计往往会导致大量的对象复制。 最初的“智能指针”(std::auto_ptr)不适合在大多数集合中使用。 最近这方面的情况有所改善(TR1)

Obvious disadvantages:

  • The syntax can be horrible - some bits of template syntax in C++ are really pushing the limits of sanity, and overlap with other parts of the language (e.g. >>)

  • Lots of people don't understand the STL very well, so you might restrict your audience.

  • Error messages tend to be hideously complicated.

  • The design of the STL collections tends to lead to a lot of copying of objects. The original 'smart pointer' (std::auto_ptr) wasn't suitable for use in most collections. Things have improved in this regard recently (TR1)

写给空气的情书 2024-07-15 02:47:34

模板有几个潜在的优点和缺点,

  • 它会扩展生成的代码的大小。
  • 模板化代码在编译时进行扩展和处理,这可能会延长编译时间。 (另一方面,可执行代码可能更有效)。
  • 错误使用 STL 元素可能会导致代码变慢
  • STL 实际上使代码更具可读性(我的观点与 Will 的观点不同)。 与任何语言或库一样,您必须理解它才能正确使用它......这对于不了解它的人来说是一个缺点。
  • 如果您在元编程意义上使用模板(不要与使用 STL 混淆),则代码看起来像是与 C++ 完全不同的语言。 解析代码实际执行的操作可能会更困难。 (OTOH,做得对 - 元编程让您专注于架构和设计;它还为编译时和运行时带来更多错误。当您拥有关键功能并且可以捕获错误编码的片段时,这是一个巨大的胜利在编译时而不是让客户在操作期间捕获它!)

话虽如此,我们使用 C++ 和模板(在某些领域还使用元编程技术)来使我们的整体代码库受益。 该代码比没有模板时的代码稍大,但性能和可维护性的权衡超过了代码的大小。 我们确实有熟练/经验丰富的 C++ 程序员致力于开发和维护代码。

如果您使用缺点来决定是否使用 C++ 功能/库 - 请确保您同等地权衡该语言的优点以及您的项目/产品/公司愿意权衡的优点。 希望这可以帮助。

编辑:我忘记提及的另一个主要缺点 - 可移植性。 如果您需要编写可移植代码,模板可能不是正确的方法。 当今大多数流行的编译器都支持 STL,但大多数编译器并非全部。 元编程技术可能是可移植性的真正杀手,因此这是决定其使用适当性的明确考虑因素。

There are several potential benefits and drawbacks

  • Templates expand the size of the resulting code.
  • Templated code is expanded and processed at compile time which may make compile times longer. (On the other hand, executable code may be more efficient).
  • Mis-used STL elements can result in slower code
  • The STL actually makes code more readable (my opinion differs from Will's). Like any language or library, you have to understand it to use it appropriately... which is a drawback for people who don't know it.
  • If you are using templates in a meta-programming sense (don't confuse w/ using the STL), the code looks like a language completely different from C++. It can be harder to parse through what the code is actually doing. (OTOH, done right - meta-programming makes you focus on architecture and design; it also brings more of the errors to compile time vs. runtime. This is a big win when you have a critical feature and you can catch an incorrectly coded piece at compile time rather than having a customer catch it during operation!)

Having said that, we use C++ and templates (and in some areas, meta-programming techniques) to the benefit of our overall code base. The code is slightly larger than it might be without templates, but the trade-offs in performance and maintainability outweigh the size. We do have skilled/experienced C++ programmers working on developing and maintaining the code.

If you're using drawbacks to decide whether to use C++ features/libraries or not - make sure you equally weigh the benefits both for the language and what your project/product/company is willing to trade off. Hope this helps.

Edit: One other major drawback I forgot to mention - portability. If you need to write portable code, templates may not be the right way to go. Most popular compilers today support the STL, however most is not all. The meta-programming techniques can be real killers to portability, so that is a definite consideration for deciding appropriateness of its use.

要走就滚别墨迹 2024-07-15 02:47:34

用于嵌入式设备编程(在我的例子中是智能手机)。 由于担心生成的代码大小(少量 RAM 和磁盘空间),不鼓励使用模板。 此外,编译器非常古老,可能无法处理一些与模板相关的构造。

For embedded device programming (in my case -- smartphones). Templates are discouraged because of the concern for generated code size (small amount of RAM and disk space). Also the compilers are pretty ancient and probably can't handle some template related constructs.

药祭#氼 2024-07-15 02:47:34
  1. 严重滥用模板(特别是
    模板元编程和 Boost
    成瘾)可能会导致过度
    编译和链接时间长。

  2. 你最终也会得到可执行文件
    具有相当大的
    (未剥离的)二进制文件,但通常
    这不是一个可怕的问题。

  3. 设计不当的模板也会
    进一步增加代码重复
    加剧可执行文件的大小
    问题。

  4. 对于具有大的类模板
    实施还需要
    考虑这样一个事实:使用
    对他们来说,模板意味着移动
    整个类主体放入标题中
    某处。 这个地方还有很多
    如果模板加载到链接器上
    用于多个地方。

  5. 来自大量模板化代码的错误消息可能会让外行人望而生畏,并且很少像从非模板化代码中得到的错误消息那样清晰。

    来自大量模板化代码的错误消息

也就是说,对于大多数应用程序来说,模板是代码重用的绝佳工具,有助于提升从重新实现到重用代码的讨论水平; 这些问题很少会胜过好处。

  1. Heavy template abuse (in particular
    template meta-programming and Boost
    addiction) can lead to excessively
    long compile and link times.

  2. You also wind up with executables
    that have considerably larger
    (unstripped) binaries, but generally
    that isn't a terrible issue.

  3. Poorly designed templates can also
    increase code duplication further
    exacerbating the executable size
    issue.

  4. For class templates with large
    implementations also need to
    consider the fact that using a
    template for them means moving the
    entire class body into a header
    somewhere. This places a lot more
    load on the linker if the template
    is used in multiple places.

  5. Error messages from heavily templated code can be daunting to the uninitiated and are rarely if ever as clear as the error messages you get from untemplated code.

That said, for most applications templates are a wonderful tool for code reuse and help lift the level of discourse from reimplementing to reusing code; rarely do these issues trump the benefits.

愛放△進行李 2024-07-15 02:47:34

套用现代 C++ 设计名声的 Andrei Alexandrescu 的话。 模板是多重继承的正交结构。 它们都有互补的权衡和利益。 模板具有丰富的机制,但模板的专业化无法扩展。

To paraphrase Andrei Alexandrescu of Modern C++ Design fame. Template are an orthogonal structure to multiple inheritance. They both have complementary trade-offs and benefits. Templates have rich mechanics but specialization of templates does not scale.

方圜几里 2024-07-15 02:47:34

模板的目标是提供具有最小性能损失的抽象。 在大多数情况下,好处大于坏处。 模板的大多数问题都来自编译器和调试器支持。

我对模板最讨厌的是:由于标头依赖性,它击败了智能构建系统。 与开发纯粹的基于 OO 的系统相比,开发模板代码往往会导致更多的未修改代码的重新编译,特别是如果后者很好地使用了 DIP(依赖倒置原则)。 这加剧了编译缓慢的问题。 OTOH,如今更快的开发硬件使事情比以前更容易忍受。

至于STL(以及Boost),他们的目标是提供可移植且相当高效的数据结构和算法。 它们不一定是某些性能关键型应用程序的最佳选择。 例如:虽然 hash_map (tr1/unordered_map) 在一般情况下表现得相当好,但特殊用途的哈希表(例如,谷歌稀疏/密集哈希表库)可以大大优于在内存使用或速度方面的通用 STL 实现。

The goal of template is to provide abstraction with minimal performance penalty. In most cases, benefits outweigh drawbacks. Most of the issues with templates are from compiler and debugger support.

My pet peeve about template: it defeats smart build system due to header dependencies. Developing template code tends to cause a lot more recompilation of untouched code than developing a pure OO based system, especially if the latter use the DIP (dependency inversion principle) well. This exacerbates the slow compilation problem. OTOH, faster dev hardware these days make things much more tolerable than before.

As for STL (as well as Boost), their goal is to provide portable and reasonably efficient data structure and algorithms. They're not necessary the best choice for certain performance critical applications. For example: although hash_map (tr1/unordered_map) performs reasonably well for average cases, special purpose hash tables (e.g., the google sparse/dense hash table library) can greatly outperform generic STL implementations in terms of memory usage or speed.

无法回应 2024-07-15 02:47:34

有很多支持和反对 C++ 模板的哲学(充其量)争论,但我最倾​​向于接受的一个是,它们在编译时实例化的机制会产生大量的代码膨胀。

虽然这通常不是一个大问题,但当您为二进制大小限制非常有限的嵌入式系统编写代码时,它会产生重大影响。

There are a lot of philosophical (at best) arguments for and against C++ templates, but the one that I tend to accept the most is that the mechanism by which they are instantiated at compile time generates a considerable amount of code bloat.

While this isn't typically much of a concern, when you're writing code for an embedded system with very limiting restrictions on binary size it makes a significant impact.

沫雨熙 2024-07-15 02:47:34

在 MSVC 实现中,std::string 每个字符串的开销为 26 个字节,即使字符串为空也是如此。 如果您只使用 char*,则每个字符串将占用 4 个字节。

In the MSVC implementation, std::string has an overhead of 26 bytes PER STRING, even if the string is empty. If you were doing just char*, it would be 4 bytes per string.

一城柳絮吹成雪 2024-07-15 02:47:34

复杂的 STL 容器(以及任何复杂的 C++ 类)使调试变得更加困难。

除了前面提到的不可读的错误消息之外,当前的调试器通常很少支持处理 STL 结构。 例如,在运行时检查本机 C 数组比检查向量数组要容易得多。 容器。

希望情况会随着时间而改变。
除此之外,模板也很棒。

Complex STL containers (and for that matter any complex C++ class) make debugging much more difficult.

Besides the unreadable error messages mentioned before, there is usually very little support in current debuggers for handling STL constructs. For example, it is much easier to examine a native C array at runtime, than a vector<> container.

Hopefully the situation will change with time.
Other than that, templates are wonderful.

ˉ厌 2024-07-15 02:47:34

其中之一可能是它们很难翻译成其他不支持 C# 和 Java 等模板的面向对象语言,因此如果您有一个来自这些语言的开发人员团队,他们将面临更陡峭的学习曲线。

One might be that they translate poorly to other object-oriented languages that don't support templates such as C# and Java, so if you have a developer group coming from those languages, they will face a steeper learning curve.

微暖i 2024-07-15 02:47:34

模板的实例化方式要求您在跨翻译单元共享模板时注意如何声明和定义模板。 《C++ 模板:完整指南》一书是有关如何处理此问题的良好信息来源。

模板的编译器和链接器错误消息往往非常非常冗长。 你必须习惯这一点,我认为有一些脚本/工具可以使它们更具可读性,但我对它们没有任何经验。

但除此之外,模板也很棒!

The way templates get instantiated requires you to be careful about how to declare and define your templates when you share them across translation units. The book "C++ templates: The complete guide" is a good source of information about how to handle this.

Compiler and linker error messages for templates tend to be very, very verbose. You'll have to get used to that, and I think there are some scripts/tools that make them more readable, but I don't have any experience with them.

But apart from that templates are great!

彩虹直至黑白 2024-07-15 02:47:34

请参阅 模板部分。 com/c++fqa/" rel="nofollow noreferrer">C++ FQA [原文如此] 有很多不使用模板的充分理由。

See the templates section of the C++ FQA [sic] for lots of good reasons to not use templates.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文