28

The book C++ Primer, 5th edition by Stanley B. Lippman (ISBN 0-321-71411-3/978-0-321-71411-4) mentions:

An [std::]array is a safer, easier-to-use alternative to built-in arrays.

What's wrong with built-in arrays?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
omidh
  • 2,526
  • 2
  • 20
  • 37
  • 2
    Not directly answering the question, but arrays don't really fit C++'s primary object-oriented paradigm. Something like a `std::vector` feels more objecty. – Isaac Woods Oct 24 '15 at 15:20
  • 4
    What do you think after reading the book? Does it not explain this claim? Doesn't it explain what it means with "safer"? Maybe the book is just not worth the paper it's written on...? – Ulrich Eckhardt Oct 24 '15 at 15:22
  • 6
    @IsaacWoods: Nonsense. C++ is not an "object-oriented" language (C++ is multi-paradigm). And, even if it were, `std::array` is precisely as "objecty" as `std::vector` is. – Lightness Races in Orbit Oct 24 '15 at 15:23
  • 1
    When you cite a book, please include the author's name, and the full book title (including edition number). Also, ideally, for convenience, page/chapter number. – Lightness Races in Orbit Oct 24 '15 at 15:27
  • @LightnessRacesinOrbit The C++ standard library is object-oriented. A huge number of C++ features are based around the object-oriented paradigm. Also, not sure if you noticed the use of the word **primarily**. – Isaac Woods Oct 24 '15 at 15:28
  • 6
    @IsaacWoods: The C++ standard library is absolutely _not_ object-oriented! It is **multi-paradigm**. And you did not address my point that it doesn't matter either way, since "arrays don't really fit ..." isn't true. – Lightness Races in Orbit Oct 24 '15 at 15:30
  • 2
    You may want to consider re-applying my edit, which makes your quote not be self-contradictory. – Johannes Schaub - litb Oct 24 '15 at 15:34
  • 2
    100% of my bugs, and more, are due to invalid array accesses. –  Oct 24 '15 at 17:00
  • 1
    @Yves: That is not solved by using another array implementation. It can only be solved by (a) using another array implementation and only ever accessing its elements through bounds-aware member functions, (b) writing better code. I choose (b) over the performance penalties of (a), any day! – Lightness Races in Orbit Oct 24 '15 at 18:48
  • @YvesDaoust: Actually, a and b are sometimes but not always contradictions, depending on circumstances. Rigorous testing is needed either way. – Deduplicator Oct 24 '15 at 22:01
  • 1
    @LightnessRacesinOrbit: "(b) writing better code": haha ! If you know the trick to write bug free, let me know. –  Oct 24 '15 at 22:03
  • @YvesDaoust: "Better code" and "bug free code" are not the same thing, though the former helps increase the chance of achieving the latter. – Lightness Races in Orbit Oct 24 '15 at 22:36

7 Answers7

31
  1. A built-in array is a contiguous block of bytes, usually on the stack. You really have no decent way to keep useful information about the array, its boundaries or its state. std::array keeps this information.

  2. Built-in arrays are decayed into pointers when passed from/to functions. This may cause:

    • When passing a built-in array, you pass a raw pointer. A pointer doesn't keep any information about the size of the array. You will have to pass along the size of the array and thus uglify the code. std::array can be passed as reference, copy or move.

    • There is no way of returning a built-in array, you will eventually return a pointer to local variable if the array was declared in that function scope. std::array can be returned safely, because it's an object and its lifetime is managed automatically.

  3. You can't really do useful stuff on built-in arrays such as assigning, moving or copying them. You'll end writing a customized function for each built-in array (possibly using templates). std::array can be assigned.

  4. By accessing an element which is out of the array boundaries, you are triggering undefined behaviour. std::array::at will preform boundary checking and throw a regular C++ exception if the check fails.

  5. Better readability: built in arrays involves pointers arithmetic. std::array implements useful functions like front, back, begin and end to avoid that.

Let's say I want to sort a built-in array, the code could look like:

int arr[7] = {/*...*/};
std::sort(arr, arr+7);

This is not the most robust code ever. By changing 7 to a different number, the code breaks.

With std::array:

std::array<int,7> arr{/*...*/};
std::sort(arr.begin(), arr.end());

The code is much more robust and flexible.

Just to make things clear, built-in arrays can sometimes be easier. For example, many Windows as well as UNIX API functions/syscalls require some (small) buffers to fill with data. I wouldn't go with the overhead of std::array instead of a simple char[MAX_PATH] that I may be using.

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
David Haim
  • 25,446
  • 3
  • 44
  • 78
  • 7
    `std::sort(std::begin(arr), std::end(arr))` works perfectly well with both – Ben Voigt Oct 24 '15 at 19:12
  • what's wrong with `std::copy`? And anyway, you *don't* want to assign arrays, they are big. Also, if you need something fancier neither works, you need a danymic container. – Deduplicator Oct 24 '15 at 22:08
  • `std::array can be passed as reference, copy or move.` But the function you call must either be ready to accept the array of the size you're passing in, or be templated, which is not much nicer than passing size as a second argument (sometimes it is though, but not always). – Ruslan Oct 25 '15 at 11:51
26

It's hard to gauge what the author meant, but I would guess they are referring to the following facts about native arrays:

  • they are raw
    There is no .at member function you can use for element access with bounds checking, though I'd counter that you usually don't want that anyway. Either you're accessing an element you know exists, or you're iterating (which you can do equally well with std::array and native arrays); if you don't know the element exists, a bounds-checking accessor is already a pretty poor way to ascertain that, as it is using the wrong tool for code flow and it comes with a substantial performance penalty.

  • they can be confusing
    Newbies tend to forget about array name decay, passing arrays into functions "by value" then performing sizeof on the ensuing pointer; this is not generally "unsafe", but it will create bugs.

  • they can't be assigned
    Again, not inherently unsafe, but it leads to silly people writing silly code with multiple levels of pointers and lots of dynamic allocation, then losing track of their memory and committing all sorts of UB crimes.

Assuming the author is recommending std::array, that would be because it "fixes" all of the above things, leading to generally better code by default.

But are native arrays somehow inherently "unsafe" by comparison? No, I wouldn't say so.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • 3
    It'd be helpful to explain for the asker and other C++ learners what's poor about a bounds-checking accessor, how much of a penalty it is in the scheme of things, and what's a better approach. This assumes the programmer has learned the ins and outs of arrays (including the ways they aren't really the same as pointers) and is diligent about array sizing. The high number of buffer overrun attacks shows that we can't rely on this. – Jerry101 Oct 24 '15 at 16:32
  • 2
    @Jerry101: The topic of bounds checking has been well-covered elsewhere and doesn't need reproducing here! My answer is not intended to be a fully-encapsulated how-to guide on C++. But, for your benefit and in brief, the way to detect buffer overruns is not to add bounds checking to your entire program, but to write typesafe code using the standard library where possible and, where not, use assertions and perform testing. – Lightness Races in Orbit Oct 24 '15 at 16:58
  • 2
    +1 for explicitly stating that native arrays aren't inherently less safe. I generally use real arrays as opposed to the standard library counterpart unless there's a solid reason not to. – Columbo Oct 24 '15 at 18:30
6

How is std::array safer and easier-to-use than a built-in array?

It's easy to mess up with built-in arrays, especially for programmers who aren't C++ experts and programmers who sometimes make mistakes. This causes many bugs and security vulnerabilities.

  • With a std::array a1, you can access an element with bounds checking a.at(i) or without bounds checking a[i]. With a built-in array, it's always your responsibility to diligently avoid out-of-bounds accesses. Otherwise the code can smash some memory that goes unnoticed for a long time and becomes very difficult to debug. Even just reading outside an array's bounds can be exploited for security holes like the Heartbleed bug that divulges private encryption keys.
  • C++ tutorials may pretend that array-of-T and pointer-to-T are the same thing, then later tell you about various exceptions where they are not the same thing. E.g. an array-of-T in a struct is embedded in the struct, while a pointer-to-T in a struct is a pointer to memory that you'd better allocate. Or consider an array of arrays (such as a raster image). Does auto-increment the pointer to the next pixel or the next row? Or consider an array of objects where an object pointer coerces to its base class pointer. All this is complicated and the compiler doesn't catch mistakes.
  • With a std::array a1, you can get its size a1.size(), compare its contents to another std::array a1 == a2, and use other standard container methods like a1.swap(a2). With built-in arrays, these operations take more programming work and are easier to mess up. E.g. given int b1[] = {10, 20, 30}; to get its size without hard-coding 3, you must do sizeof(b1) / sizeof(b1[0]). To compare its contents, you must loop over those elements.
  • You can pass a std::array to a function by reference f(&a1) or by value f(a1) [i.e. by copy]. Passing a built-in array only goes by reference and confounds it with a pointer to the first element. That's not the same thing. The compiler doesn't pass the array size.
  • You can return a std::array from a function by value, return a1. Returning a built-in array return b1 returns a dangling pointer, which is broken.
  • You can copy a std::array in the usual way, a1 = a2, even if it contains objects with constructors. If you try that with built-in arrays, b1 = b2, it'll just copy the array pointer (or fail to compile, depending on how b2 is declared). You can get around that using memcpy(b1, b2, sizeof(b1) / sizeof(b1[0])), but this is broken if the arrays have different sizes or if they contain elements with constructors.
  • You can easily change code that uses std::array to use another container like std::vector or std::map.

See the C++ FAQ Why should I use container classes rather than simple arrays? to learn more, e.g. the perils of built-in arrays containing C++ objects with destructors (like std::string) or inheritance.

Don't Freak Out About Performance

Bounds-checking access a1.at(i) requires a few more instructions each time you fetch or store an array element. In some inner loop code that jams through a large array (e.g. an image processing routine that you call on every video frame), this cost might add up enough to matter. In that rare case it makes sense to use unchecked access a[i] and carefully ensure that the loop code takes care with bounds.

In most code you're either offloading the image processing code to the GPU, or the bounds-checking cost is a tiny fraction of the overall run time, or the overall run time is not at issue. Meanwhile the risk of array access bugs is high, starting with the hours it takes you to debug it.

Jerry101
  • 12,157
  • 5
  • 44
  • 63
5

The only benefit of a built-in array would be slightly more concise declaration syntax. But the functional benefits of std::array blow that out of the water. I would also add that it really doesn't matter that much. If you have to support older compilers, then you don't have a choice, of course, since std::array is only for C++11. Otherwise, you can use whichever you like, but unless you make only trivial use of the array, you should prefer std::array just to keep things in line with other STL containers (e.g., what if you later decide to make the size dynamic, and use std::vector instead, then you will be happy that you used std::array because all you will have to change is probably the array declaration itself, and the rest will be the same, especially if you use auto and other type-inference features of C++11.

std::array is a template class that encapsulate a statically-sized array, stored inside the object itself, which means that, if you instantiate the class on the stack, the array itself will be on the stack. Its size has to be known at compile time (it's passed as a template parameter), and it cannot grow or shrink.

Arrays are used to store a sequence of objects Check the tutorial: http://www.cplusplus.com/doc/tutorial/arrays/

A std::vector does the same but it's better than built-in arrays (e.g: in general, vector hasn't much efficiency difference than built in arrays when accessing elements via operator[]): http://www.cplusplus.com/reference/stl/vector/

The built-in arrays are a major source of errors – especially when they are used to build multidimensional arrays. For novices, they are also a major source of confusion. Wherever possible, use vector, list, valarray, string, etc. STL containers don't have the same problems as built in arrays

So, there is no reason in C++ to persist in using built-in arrays. Built-in arrays are in C++ mainly for backwards compatibility with C.

If the OP really wants an array, C++11 provides a wrapper for the built-in array, std::array. Using std::array is very similar to using the built-in array has no effect on their run-time performance, with much more features.

Unlike with the other containers in the Standard Library, swapping two array containers is a linear operation that involves swapping all the elements in the ranges individually, which generally is a considerably less efficient operation. On the other side, this allows the iterators to elements in both containers to keep their original container association. Another unique feature of array containers is that they can be treated as tuple objects: The header overloads the get function to access the elements of the array as if it was a tuple, as well as specialized tuple_size and tuple_element types.

Anyway, built-in arrays are all ways passed by reference. The reason for this is when you pass an array to a function as a argument, pointer to it's first element is passed.

when you say void f(T[] array) compiler will turn it into void f(T* array) When it comes to strings. C-style strings (i.e. null terminated character sequences) are all ways passed by reference since they are 'char' arrays too.

STL strings are not passed by reference by default. They act like normal variables. There are no predefined rules for making parameter pass by reference. Even though the arrays are always passed by reference automatically.


vector<vector<double>> G1=connectivity( current_combination,M,q2+1,P );
vector<vector<double>> G2=connectivity( circshift_1_dexia(current_combination),M,q1+1,P );

This could also be copying vectors since connectivity returns a vector by value. In some cases, the compiler will optimize this out. To avoid this for sure though, you can pass the vector as non-const reference to connectivity rather than returning them. The return value of maxweight is a 3-dimensional vector returned by value (which may make a copy of it). Vectors are only efficient for insert or erase at the end, and it is best to call reserve() if you are going to push_back a lot of values. You may be able to re-write it using list if you don't really need random access; with list you lose the subscript operator, but you can still make linear passes through, and save iterators to elements, rather than subscripts.

With some compilers, it can be faster to use pre-increment, rather than post-increment. Prefer ++i to i++ unless you actually need to use the post-increment. They are not the same.

Anyway, vector is going to be horribly slow if you are not compiling with optimization on. With optimization, it is close to built-in arrays. Built-in arrays can be quite slow without optimization on also, but not as bad as vector.

  • 2
    This doesn't answer what's unsafe about arrays. How is "blows that out of the water" compatible with "doesn't matter that much"? – Jerry101 Oct 24 '15 at 16:23
  • I don't know for which motivation should I repeat the same things other users already answered. It's another note, I don't want to steal people's answers. –  Oct 24 '15 at 16:27
  • 1
    On SO, each answer should be a self-contained answer to the question. It's OK to overlap other answers. Even if an answer adds no new points, it's still valuable if it *explains* them more clearly to people leaning C++. – Jerry101 Oct 24 '15 at 16:42
2

std::array has the at member function which is safe. It also have begin, end, size which you can use to make your code safer.

Raw arrays don't have that. (In particular, when raw arrays are decayed to pointers -e.g. when passed as arguments-, you lose any size information, which is kept in the std::array type since it is a template with the size as argument)

And a good optimizing C++11 compiler will handle std::array (or references to them) as efficiently as raw arrays.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
2

Built-in arrays are not inherently unsafe - if used correctly. But it is easier to use built-in arrays incorrectly than it is to use alternatives, such as std::array, incorrectly and these alternatives usually offer better debugging features to help you detect when they have been used incorrectly.

Neil Kirk
  • 21,327
  • 9
  • 53
  • 91
2

Built-in arrays are subtle. There are lots of aspects that behave unexpectedly, even to experienced programmers.

std::array<T, N> is truly a wrapper around a T[N], but many of the already mentioned aspects are sorted out for free essentially, which is very optimal and something you want to have.

These are some I haven't read:

  1. Size: N shall be a constant expression, it cannot be variable, for both. However, with built-in arrays, there's VLA(Variable Length Array) that allows that as well.

    Officially, only C99 supports them. Still, many compilers allow that in previous versions of C and C++ as extensions. Therefore, you may have

    int n; std::cin >> n;
    int array[n]; // ill-formed but often accepted
    

    that compiles fine. Had you used std::array, this could never work because N is required and checked to be an actual constant expression!

  2. Expectations for arrays: A common flawed expectation is that the size of the array is carried along with the array itself when the array isn't really an array anymore, due to the kept misleading C syntax as in:

    void foo(int array[])
    {
        // iterate over the elements
        for (int i = 0; i < sizeof(array); ++i)
             array[i] = 0;
    }
    

    but this is wrong because array has already decayed to a pointer, which has no information about the size of the pointed area. That misconception triggers undefined behavior if array has less than sizeof(int*) elements, typically 8, apart from being logically erroneous.

    1. Crazy uses: Even further on that, there are some quirks arrays have:

      • Whether you have array[i] or i[array], there is no difference. This is not true for array, because calling an overloaded operator is effectively a function call and the order of the parameters matters.

      • Zero-sized arrays: N shall be greater than zero but it is still allowed as an extensions and, as before, often not warned about unless more pedantry is required. Further information here. array has different semantics:

        There is a special case for a zero-length array (N == 0). In that case, array.begin() == array.end(), which is some unique value. The effect of calling front() or back() on a zero-sized array is undefined.

edmz
  • 8,220
  • 2
  • 26
  • 45
  • Re #2 - well, `std::array` has to be templated on size when passed as a function argument, and you can do the same thing with a bare array, so you technically have the same restrictions on using size within the function. But sure, `std::array` can be safer in that it _requires_ you to write this, whereas a bare array lets you accidentally invoke decay to pointer. – underscore_d Apr 19 '16 at 10:07