Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does using std::array<T, N> lead to code bloat? [duplicate]

I have seen in a few places the recommendation to use std::array over C-style arrays in C++, claiming it is a better, safer alternative with no overhead. See:

The standard container array [...] has no space overheads beyond what it needs to hold its elements, [...]. In other words, it is very much like a built-in array without the problems. (C++11 FAQ)

However, as I understand it, being a template container there will be an overhead as far as program size goes, since it will generate code for every different N an array is instanced with.

Suppose my program uses std::array in various places with several different integers for N, will this lead to bloated code? Is it negligible?

Should I worry about this for non-type template parameters in general?

like image 617
frangio Avatar asked Jul 29 '14 06:07

frangio


1 Answers

I wouldn't worry about it. If you look at the interface of std::array<T, N>, it is very small and most member functions (basically providing wrappers for pointer manipulation) are one-liners that will be completely optimized away / inlined by any decent compiler on Release mode optimization levels.

Furthermore, you don't pay for what you don't use since unused non-virtual member functions (std::array<T, N> does not have virtual member functions) of class templates are guaranteed not to be instantiated. Small Standard quote:

14.7.1 Implicit instantiation [temp.inst]

11 An implementation shall not implicitly instantiate a function template, a variable template, a member template, a non-virtual member function, a member class, or a static data member of a class template that does not require instantiation. [...]

There are also some overloaded relational operators == and < that are semantically equivalent to std::equal and std::lexicographical_compare. In practice, these operators should also be implemented in terms of these algorithms (complain to your vendor if they don't).

The only very small worry is a little extra compile-time overhead, but there should be zero code-size and run-time overhead.

Related but not identical: the Technical Report on C++ Performance did a lot of careful benchmarks on thin class wrappers around builtin types (int, double) and found close to zero overhead for 2006 compiler technology. You could repeat their testing to verify this for std::array<T,N> vs. T[N]

like image 125
TemplateRex Avatar answered Oct 05 '22 18:10

TemplateRex