STD::string 作为动态分配对象的成员参数
我希望动态分配对象集(可以是数百个)。这些对象的一部分是文本字段。因为 std::string 提供了很好的字符串操作,所以我更喜欢使用 std:string 类型的对象成员参数。
但是,std::string 是动态调整大小的对象。对我来说,这违背了包含 std::string 的动态分配对象:如果 std::string 变得比计划的大,则可能会分配内存溢出。
- 请问 std::string 是否适合作为动态分配对象的参数?
- 如何用std::string进行操作,这样才不会出现内存溢出?
- 即使动态分配数百个对象,std::string 是否适合作为成员参数?
I wish to dynamically allocate set of objects(can be several hundreds). Part of those objects are text fields. Because std::string offers nice string manipulations, I would prefer having the object member parameters of type std:string.
However, std::string is dynamically resizable object. To me, this goes against the dynamically allocated objects containing std::string: There could be allocated memory overflow, if the std::string gets larger than planned.
- Can I kindly ask for advices whether std::string is suitable as a parameter for dynamically allocated objects?
- How to manipulate with std::string, so there will not be memory overflow?
- Is std::string suitable as a member parameter even if hundreds of objects will be allocated dynamically?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你的问题有点难以解析,我认为示例代码会让这变得更容易。我是否正确地假设您有一个包含字符串的类,如下所示:
并且您想知道如何调整字符串的大小?让我尝试解释一下:
foo 类的对象的大小是固定的。字符串成员的大小也是固定的,但它在其实现中包含一个指向附加动态内存(其他地方)的指针,该内存根据字符串的内容而增长或缩小。 std::string 的实现会为您处理这个问题,您无需担心它。也不会有任何内存溢出——例如,字符串的内存与 foo 对象使用的内存块是不同的内存块。
Your question is a little difficult to parse, and sample code would have made that easier, I think. Am I right in assuming that you have a class that contains a string, like so:
and you wonder how the string is resized? Let me try and explain:
The size of objects of class foo is fixed. The size of the string member is also fixed, but it contains in its implementation a pointer to additional dynamic memory (someplace else) that it is growing or shrinking depending on the contents of the string. The implementation of std::string takes care of this for you, you don't need to worry about it. There won't be any memory overflow either - the string's memory is a different block of memory from the block used by the foo-object, for example.