简体   繁体   English

具有动态对象的std :: array是否安全?

[英]Is it safe to have a std::array of dynamic object?

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) ? 具有动态对象的std::array是否安全(例如std::array<std::string, 3> )并调整内容(字符串)的大小是否安全? (because it can be problematic to have a raw C array of strings) (因为拥有原始的C字符串数组可能会出现问题)

Yes, because std::array is a just a friendly template that wraps an underlying C style aray array. 是的,因为std::array是一个友好的模板,它包装了基础的C样式aray数组。 You can think of it as something like this: 您可以将其视为这样:

template <typename T, int size>
class Array {
...
   T vals[size];
}

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::array of strings. 将T更改为上面的字符串,您将很快意识到,对字符串数组的内容可以执行的任何操作都可以使用字符串std::array进行。 This includes resizing, deleting, whatever you can imagine. 这包括调整大小,删除大小,以及您可以想象的一切。

To think even deeper about it, think about it this way. 要更深入地思考,请以这种方式思考。 The std::array holds a string. std::array保存一个字符串。 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 case std::array ) yet another client of the string 's public interface. 字符串由任何数据结构保存的事实并不限制该字符串的功能,它只是使持有人(在本例中为std::array )成为string公共接口的另一个客户端。

As containers like std::array need to work with a large variety of types, they tend to make relatively few typically well documented assumptions on the type T passed in. Stuff like requiring that T can be copy constructed, default constructed, and assigned. 由于像std::array这样的容器需要使用各种各样的类型,因此它们往往对传入的T类型做出相对较少的通常有据可查的假设。诸如要求T可以被复制构造,默认构造和分配的东西。 Then its typically up to the implementer* of T to ensure these few assumptions are valid. 然后,通常由T的实现者*来确保这几个假设有效。

*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. 除了vector<bool>以外,这些在标准容器中很少见。

假设您的意思是调整字符串的大小,那么可以。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM