开发者

STD::string as a Member Parameter for Dynamically Allocated Objects

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?


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;
};

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜