Is it safe to have a std::array of dynamic object, for example std::array<std::string, 3>, and to resize the contents (the strings) ? (because it can be problematic to have a raw C array of strings)
Is it safe to have a std::array of dynamic object, for example std::array<std::string, 3>
Share
Yes, because
std::arrayis a just a friendly template that wraps an underlying C style aray array. You can think of it as something like this:Change T to string above and you’ll quickly realize that anything that you can do to the contents of an array of strings you can do with a
std::arrayof strings. This includes resizing, deleting, whatever you can imagine.To think even deeper about it, think about it this way. The
std::arrayholds a string. The string has no idea where its being held. The array might tell the string to make a copy of itself (through a copy constructor or assignment), when say the array itself is assigned. However, this is its entirely through the string’s public interface. The fact that the string is being held by any data structure doesn’t limit that string’s functionality, it just makes the holder (in this casestd::array) yet another client of thestring‘s public interface.As containers like
std::arrayneed to work with a large variety of types, they tend to make relatively few typically well documented assumptions on the typeTpassed in. Stuff like requiring that T can be copy constructed, default constructed, and assigned. Then its typically up to the implementer* ofTto ensure these few assumptions are valid.*There is a very advanced topic called template specialization where one could write a specialized version of array just for say “string”. Aside from
vector<bool>these are pretty rare with the standard containers.