2

Why won't this build in VS 2010 C++?

typedef float test[10];
std::vector<test> test_me(100); // wanted initial capacity of 100

While this builds fine

typedef float test[10];
std::vector<test> test_me_now;
  • Won't build in GCC either: `error: invalid array assignment`. The second form compiles, but the result `vector` is useless. – Fred Foo Nov 09 '12 at 16:52
  • 1
    See this question for a possible workaround [Why declare a stuct that only contains an array?](http://stackoverflow.com/questions/6966570/why-declare-a-struct-that-only-contains-an-array-in-c) – Bo Persson Nov 09 '12 at 17:04

3 Answers3

6

Arrays are neither copy constructible, nor move constructible. std::vector requires at least one of those for most operations. Or at least, the operations that involve actually putting things into the vector. Since the default constructor doesn't put anything into the vector, there's no problems using it.

The unbecoming behavior of built-in arrays is why std::array was invented.

Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274
4

This

std::vector<test> test_me(100);

will attempt to call the default constructor of test, test(), which doesn't exist. If you want increased capacity, as opposed to a vector with 100 elements, try

std::vector<test> test_me_now;
test_me_now.reserve(100);

although it is hard to see how you could use such a vector, since most operations will be invalid.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
1

23.1/3 seems pretty clear about this:

The type of objects stored in these components must meet the requirements of CopyConstructible types (20.1.3), and the additional requirements of Assignable types.

C-style arrays are neither CopyConstructible nor Assignable so they can't be stored in containers. Presumably this means you've entered into the realm of undefined behavior so the compiler can do whatever it likes in both cases.

Mark B
  • 95,107
  • 10
  • 109
  • 188