How do string istreams work?

0

To get a std::string , pointers of type char are required, as far as I know. However, to get a pointer, you have to allocate memory (necessarily, or there will be runtime error , Segmentation Fault ). However, it may contain too much data or little data; everything depends on the user / file. How does the dynamic memory allocation of a std::string work?

Simply put: In std::istream , there is only one way to know the size of the data to be next input . How does std::string allocate the necessary space, without knowing it and without using unnecessary memory?

Example:

friend std::ifstream& operator>>(std::ifstream& ifs, std::string str)
{
    char* dados; //Como eles serão alocados?
    ifs >> dados;
    str = dados;
}
    
asked by anonymous 18.05.2014 / 16:22

1 answer

0

Simple - the operator is implemented more or less like this (simplifying soooo!):

istream& operator>>(istream& input, string& s) {
   char c;
   s.clear();
   while( input.get(c) && !isspace(c) )
     s.push_back(c);
   return input;
}

where push_back takes care of, from time to time, reallocate the buffer of string s so that the new characters can fit.

    
26.05.2014 / 12:47