2

I am facing a situation where I would like to give a std::string a size, but without filling it with characters.

Unfortunatly, no constructor allow to do that, and the only function to set the size of std::string, called resize(size_t size, char n) also require a character to fill the std::string..

Is there any way to do this?

It's probably going to be a no, but I would like to be sure I didn't miss anything, or if they are any alternative means to do it.

Thanks in advance.

souki
  • 1,305
  • 4
  • 23
  • 39
  • 3
    Why do you want to resize it without filling it with characters? What problem are you trying to solve? – UnholySheep Jul 05 '18 at 09:17
  • 4
    you can https://en.cppreference.com/w/cpp/string/basic_string/resize – wtom Jul 05 '18 at 09:18
  • @UnholySheep I am reading data from a socket with `boost::asio`, using `async_read()`. It takes a buffer as parameter, created with a string, and returns the value only when the buffer is full or the connexion has been lost. As the buffer has a size of 0, `async_read` considers it is full and don't fill it. – souki Jul 05 '18 at 09:20
  • oh you're right @wtom, I missed that. Write it as an anwser and I will accept it – souki Jul 05 '18 at 09:20
  • 3
    A buffer sounds like you want a `std::vector` (or `std::vector` if you are using C++17), not a `std::string` – UnholySheep Jul 05 '18 at 09:22
  • @UnholySheep, no it's a `boost::asio::buffer` and the constructor I am using takes a `std::string` as parameter. – souki Jul 05 '18 at 09:23
  • @souki. No, it's not exactly what you want. "The first version initializes new characters to CharT()". I would prefer vector – wtom Jul 05 '18 at 09:24
  • @UnholySheep, well actually you might be right, since there are tons of constructors, and some of them take `std::vector<>` as parameters. One question thought, why is it better than `std::string` in my case ? – souki Jul 05 '18 at 09:28
  • there seems to also be a constructor which takes a `string` and a size (or max size), maybe you can use this and pass an empty string – Karsten Koop Jul 05 '18 at 09:29
  • https://en.cppreference.com/w/cpp/string/basic_string/reserve – Bob__ Jul 05 '18 at 09:40
  • 3
    @suoki. I would say in general terms std::string is designed to be treated as container for zero terminated C string, not memory buffer. In semantics, memory allocation policies, terminating '\0', etc. – wtom Jul 05 '18 at 09:46
  • Isn't `std::vector` slower than `std::string` though? – souki Jul 05 '18 at 09:52
  • 1
    Slower how? How did you compare their performance? – UnholySheep Jul 05 '18 at 10:00
  • Read it in some SO anwser, can't find it back though. But it's just a question. – souki Jul 05 '18 at 10:02
  • 1
    highly unlikely. especially if you reuse memory that is allocated once =) https://stackoverflow.com/questions/11358879/benefits-of-vectorchar-over-string – wtom Jul 05 '18 at 10:04
  • @wtom good to know, thanks! – souki Jul 05 '18 at 11:50

0 Answers0