Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
152 views
in Technique[技术] by (71.8m points)

c++ - Why is there no reserving constructor for std::string?

There are several constructors for std::string. I was looking for a way to avoid reallocation and I'm surprised that there is a fill constructor but no "reserve" constructor.

 std::string (size_t n, char c);

but no

 std::string (size_t n);

So do I have to call reserve() after it already allocated the default (16 bytes in my case), just to immediately reallocate it?

Is there a reason why there is no such constructor to reserve space directly when the object is created, instead of having to do it manually? Or am I missing something and there is some way to do this?

Using the fill constructor is a waste of time, because it will loop through the memory just to get overwritten, and also cause a wrong size, because s.length() reports N instead of 0.

question from:https://stackoverflow.com/questions/32738879/why-is-there-no-reserving-constructor-for-stdstring

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is all guesswork, but I'll try.

If you already know the size of the string that you need, you will most likely be copying data from somewhere else, e.g. from another string. In that case, you can call one of the constructors that accept char * or const std::string & to copy the data immediately.

Also, I can't see why using reserve right after constructing a string is a bad thing. While it is implementation-defined, I would assume that it would make sense for this code:

std::string str;
str.reserve(100);

to allocate memory for a total of 100 elements, not 116 (as in "allocate 16 first, then free them and allocate 100 more"), thus having no performance impact over the non-existent reserve constructor.

Also, if you just want an empty string without the default allocation at all, you can presumably use std::string str(0, ' '); which invalidates the "Using the fill constructor is a waste of time" point.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...