user334911
user334911

Reputation:

C++ vector of array of floats build trouble

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;

Upvotes: 2

Views: 170

Answers (3)

Mark B
Mark B

Reputation: 96281

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.

Upvotes: 1

Benjamin Lindley
Benjamin Lindley

Reputation: 103733

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.

Upvotes: 6

juanchopanza
juanchopanza

Reputation: 227478

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.

Upvotes: 4

Related Questions