How do the istreams of a string work?

Asked

Viewed 121 times

0

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

Put simply: in a std::istream, there is only how to know the size of the data to be allocated afterward of input. As the std::string allocates 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;
}
  • char* dados; ifs >> datos; This is wrong! Operator>> with char* expects you to have enough memory allocated on the pointer. The way it is is Undefined behaviour.

  • @Guilhermebernal of course it is! This is not my doubt and was not what I commented? I want to know how it allocates memory to occupy the entire buffer. If so, we could not use threads with, for example, a string and a file and another with a string and Std::Cin. I also advise deleting the answer

  • -1. The question nay is clear. I still don’t understand what the point is. If it is to read a stream string, the buffer is allocated with an initial size and grows as needed until everything has been read. What threads have to do with it? (The answer is already deleted half an hour.)

  • @Guilhermebernal re-edited. See "simplifying".

  • @Lucashenrique I think the question you want to ask is "como um std::istream gerencia a alocação de memória quando está fazendo a entrada de um std::string?" and the answer, as I put it below, is "usa std::string::push_back (ou std::back_insert_iterator, que dá na mesma), o qual fará a realocação do buffer interno da string quando for necessário para que caibam mais caracteres"

1 answer

0


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

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 is in charge of relocating the buffer from time to time string s so that the new characters can fit.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.