STD::string 作为动态分配对象的成员参数 [英] STD::string as a Member Parameter for Dynamically Allocated Objects

查看:64
本文介绍了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.

然而,std::string 是可动态调整大小的对象.对我来说,这与包含 std::string 的动态分配对象背道而驰:如果 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.

  • 请问 std::string 是否适合作为动态分配对象的参数?
  • 如何操作std::string,才不会出现内存溢出?
  • 即使将动态分配数百个对象,std::string 是否适合作为成员参数?

推荐答案

你的问题有点难以解析,我认为示例代码会让这更容易.我是否正确假设您有一个包含字符串的类,如下所示:

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:

class foo {
  public:
    std::string str;
};

你想知道字符串是如何调整大小的?让我试着解释一下:foo 类对象的大小是固定的.字符串成员的大小也是固定的,但它在其实现中包含一个指向额外动态内存(其他地方)的指针,它根据字符串的内容增长或缩小.std::string 的实现会为您解决这个问题,您无需担心.也不会有任何内存溢出 - 例如,字符串的内存是与 foo 对象使用的块不同的内存块.

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.

这篇关于STD::string 作为动态分配对象的成员参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆