Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there no reserving constructor for std::string?

Tags:

c++

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.

like image 945
Devolus Avatar asked Sep 23 '15 11:09

Devolus


People also ask

How do you reserve a string?

Consider a string str and l is planned length of the string. Its syntax would be: str. reserve(l);

How do you allocate a space in a string C++?

The code calls operator new[] to allocate memory for 10 string object, then call the default string constructor for each array element. In the way, when the delete operator is used on an array, it calls a destructor for each array element and then calls operator delete[] to deallocate the memory.

Does std :: string allocate?

The object str (it is the instance of the class std::string ) is allocated in the stack. However, the string data itself MAY BE allocated in the heap. It means the object has an internal pointer to a buffer that contains the actual string.

Does STD string initialize empty?

the initializations are the same: the ctor of std::string sets it to the empty string.


1 Answers

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.

like image 139
SingerOfTheFall Avatar answered Oct 14 '22 02:10

SingerOfTheFall