Question

Unquestionably, I would choose to use the STL for most C++ programming projects. The question was presented to me recently however, "Are there any cases where you wouldn't use the STL?"...

The more I thought about it, the more I realized that perhaps there SHOULD be cases where I choose not to use the STL... For example, a really large, long term project whose codebase is expected to last years... Perhaps a custom container solution that precisely fits the projects needs is worth the initial overhead? What do you think, are there any cases where you would choose NOT to STL?

Was it helpful?

Solution

Projects with strict memory requirements such as for embedded systems may not be suited for the STL, as it can be difficult to control and manage what's taken from and returned to the heap. As Evan mentioned, writing proper allocators can help with this, but if you're counting every byte used or concerned with memory fragmentation, it may be wiser to hand-roll a solution that's tailored for your specific problem, as the STL has been optimized for the most general usage.

You may also choose not to use STL for a particular case because more applicable containers exist that are not in the current standard, such as boost::array or boost::unordered_map.

OTHER TIPS

The main reasons not to use STL are that:

  1. Your C++ implementation is old and has horrible template support.
  2. You can't use dynamic memory allocation.

Both are very uncommon requirements in practice.

For a longterm project rolling your own containers that overlap in functionality with the STL is just going to increase maintenance and development costs.

There are just so many advantages to using the stl. For a long term project the benefits outweigh the costs.

  1. New programmers being able to understand the containers from day one giving them more time to learn the other code in the project. (assuming they already know STL like any competent C++ programmer would)
  2. Fixing bugs in containers sucks and wastes time that could be spent enhancing the business logic.
  3. Most likely you're not going to write them as well as the STL is implemented anyways.

That being said, the STL containers don't deal with concurrency at all. So in an environment where you need concurrency I would use other containers like the Intel TBB concurrent containers. These are far more advanced using fine grained locking such that different threads can be modifying the container concurrently and you don't have to serialize access to the container.

Usually, I find that the best bet is to use the STL with custom allocators instead of replacing STL containers with hand rolled ones. The nice thing about the STL is you pay only for what you use.

I think it's a typical build vs buy scenario. However, I think that in this case I would almost always 'buy', and use STL - or a better solution (something from Boost perhaps), before rolling my own. You should be focusing most of your effort on what your application does, not the building blocks it uses.

I don't really think so. In making my own containers, I would even try to make those compatible with the STL because the power of the generic algorithms is too great to give up. The STL should at least be nominally used, even if all you do is write your own container and specialize every algorithm for it. That way, every sorting algorithm can be invoked sort(c.begin(), c.end()). If you specialize sort to have the same effect, even if it works differently.

Coding for Symbian.

STLPort does support Symbian 9, so the case against using STL is weaker than it used to be ("it's not available" is a pretty convincing case), but STL is still alien to all the Symbian libraries, so may be more trouble than just doing things the Symbian way.

Of course it might be argued on these grounds that coding for Symbian is not "a C++ programming project".

Most of the projects I have worked on had a codebase way older than any really usable version of STL - therefore we chose not to introduce it now.

One situation where this might occur is when you are already using an external library that already provides the abilities you need from the STL. For instance, my company develops an application in space-limited areas, and already uses Qt for the windowing toolkit. Since Qt provides STL-like container classes, we use those instead of adding the STL to our project.

Introduction:

STL is a great library, and useful in many cases, but it definitively don't solve all the situations. Answering STL or !STL is like answering "Does STL meet your need or does it not?"

Pros of STL

  • In most situations, STL has a container that fit for a given solution.
  • It is well documented
  • It is well known ( Programmers usually already know it, getting into a project is shorter)
  • It is tested and stable.
  • It is crossplatform
  • It is included with every compiler (does not add a 3rd library dependency)
  • STL is already implemented and ready
  • STL is shiny, ...

Contras of STL

It does not mater that you need a simple Graph, Red-Black Tree, or a very complex database of elements with an AI managing concurrent access through a quantum computer. The fact is, STL do not, and will never solve everything.

Following aspects are only a few examples, but they basically are consequence of this fact: STL is a real library with limits.

  • Exceptions: STL relay on exceptions, so if for any reason you cannot accept exceptions (e.g. safety critical), you cannot use STL. Right! exceptions may be disabled, but that does not solve the design of the STL relaying on them and will eventually carry a crash.

  • Need of specific (not yet included) data structure: graph, tree, etc.

  • Special constraints of complexity: You could discover that STL general purpose container is not the most optimal for your bottleneck code.

  • Concurrency considerations: Either you need concurrency and STL do not provide what you need (e.g. reader-writer lock cannot(easily) be used because of the bi-directional [] operator). Either you could design a container taking benefit of multi-threading for a much faster access/searching/inserting/whatever.

  • STL need to fit your needs, but the revers is also true: You need to fulfill the needs of STL. Don't try to use std::vector in a embedded micro-controller with 1K of unmanaged RAM.

  • Compatibility with other libraries: It may be that for historical reasons, the libraries you use do not accept STL (e.g. QtWidgets make intensive use of it own QList). Converting containers in both directions might be not the best solution.


Implementing your own container

After reading that, you could think: "Well, I am sure I may do something better for my specific case than STL does." WAIT!

Implementing your container correctly become very quickly a huge task: it is not only about implementing something working, you might have to:

  • Document it deeply, including limitations, algorithm complexity,etc.
  • Expect bugs, and solving them
  • Incoming additional needs: you know, this function missing, this conversion between types, etc.
  • After a while, you could want to refactor, and change all the dependencies (too late?)
  • ....

Code used that deep in the code like a container is definitively something that take time to implement, and should be though carefully.


Using 3rd party library

Not STL does not necessarily mean custom. There are plenty of good libraries in the net, some even with permissive open-source license.

Adding or not an additional 3rd party library is another topic, but it worth to be considered.

I have found problems in using STL in multi-threaded code. Even if you do not share STL objects across threads, many implementations use non-thread safe constructs (like ++ for reference counting instead of an interlocked increment style, or having non-thread-safe allocators).

In each of these cases, I still opted to use STL and fix the problems (there are enough hooks to get what you want).

Even if you opt to make your own collections, it would be a good idea to follow STL style for iterators so that you can use algorithms and other STL functions that operate only on iterators.

The main issue I've seen is having to integrate with legacy code that relies on non-throwing operator new.

I started programming C back in about 1984 or so and have never used the STL. Over the years I have rolled my own function librarys and they have evolved and grown when the STL was not stable yet and or lacked cross platform support. My common library has grown to include code by others ( mostly things like libjpeg, libpng, ffmpeg, mysql ) and a few others and I would rather keep the amount of external code in it to a minimum. I'm sure now the STL is great but frankly I'm happy with the items in my toolbox and see no need at this point to load it up with more tools. But I certainly see the great leaps and bounds that new programmers can make by using the STL without having to code all that from scratch.

Standard C++ perversely allows implementations of some iterator operations to throw exceptions. That possibility can be problematic in some cases. You might therefore implement your own simple container that is guaranteed not to throw exceptions for critical operations.

Since almost everybody who answered before me seemed so keen on STL containers, I thought it would be useful to compile a list of good reasons not to use them, from actual problems I have encountered myself.

These can be reasonably grouped into three broad categories:

1) Poor efficiency

STL containers typically run slower AND use too much memory for the job. The reason for this can be partly blamed on too generic implementations of the underlying data structures and algorithms, with additional performance costs deriving from all the extra design constrains required by the tons of API requisites that are irrelevant to the task at hand.

Reckless memory use and poor performance go hand in hand, because memory is addressed on the cache by the CPU in lines of 64 bytes, and if you don't use locality of reference to your advantage, you waste cycles AND precious Kb of cache memory.

For instance, std::list requires 24 bytes per element rather than the optimal 4.

https://lemire.me/blog/2016/09/15/the-memory-usage-of-stl-containers-can-be-surprising/

This is because it is implemented by packing two 64-bit pointers, 1 int and 4 bytes of memory padding, rather than doing anything as basic as allocating small amounts of contiguous memory and separately tracking which elements are in use, or using the pointer xor technique to store both iteration directions in one pointer.

https://en.wikipedia.org/wiki/XOR_linked_list

Depending on your program needs, these inefficiencies can and do add up to large performance hits.

2) Limitations / creeping standards

Of course, sometimes the problem is that you need some perfectly common function or slightly different container class that is just not implemented in STL, such as decrease_min() in a priority queue.

A common practice is to then to wrap the container in a class and implement the missing functionality yourself with extra state external to the container and/or multiple calls to container methods, which may emulate the desired behavior, but with a performance much lower and O() complexity higher than a real implementation of the data structure, since there's no way of extending the inner workings of the container. Alternatively you end up mashing up two or more different containers together because you simultaneously need two or more things that are fundamentally incompatible in any one given STL container, such as a minmax heap, a trie (since you need to be able to use agnostic pointers), etc.

These solutions may be ugly and add on top of the other inefficiencies, and yet the way the language is evolving the tendency is to only add new STL methods to match C++'s feature creep and ignore any of the missing core functionality.

3) Concurrency/parallelism

STL containers are not thread-safe, much less concurrent. In the present age of 16-thread consumer CPUs, it's surprising the go-to default container implementation for a modern language still requires you to write mutexes around every memory access like it's 1996. This is, for any non-trivial parallel program, kind of a big deal, because having memory barriers forces threads to serialize their execution, and if these happen with the same frequency as an STL call, you can kiss your parallel performance goodbye.

In short, STL is good as long as you don't care about performance, memory usage, functionality or parallelism. STL is of course still perfectly fine for the many times you are not bound by any of these concerns and other priorities like readability, portability, maintainability or coding speed take precedence.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top