Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to get std:string's buffer

Is there a way to get the "raw" buffer o a std::string?
I'm thinking of something similar to CString::GetBuffer(). For example, with CString I would do:

CString myPath;  
::GetCurrentDirectory(MAX_PATH+1, myPath.GetBuffer(MAX_PATH));  
myPath.ReleaseBuffer();  

So, does std::string have something similar?

like image 394
MikMik Avatar asked Oct 20 '11 13:10

MikMik


2 Answers

While a bit unorthodox, it's perfectly valid to use std::string as a linear memory buffer, the only caveat is that it isn't supported by the standard until C++11 that is.

std::string s;
char* s_ptr = &s[0]; // get at the buffer

To quote Herb Sutter,

Every std::string implementation I know of is in fact contiguous and null-terminates its buffer. So, although it isn’t formally guaranteed, in practice you can probably get away with calling &str[0] to get a pointer to a contiguous and null-terminated string. (But to be safe, you should still use str.c_str().)

Probable is key here. So, while it's not a guarantee, you should be able to rely on the principle that std::string is a linear memory buffer and you should assert facts about this in your test suite, just to be sure.

You can always build your own buffer class but when you're looking to buy, this is what the STL has to offer.

like image 68
John Leidegren Avatar answered Oct 13 '22 08:10

John Leidegren


Use std::vector<char> if you want a real buffer.

#include <vector>
#include <string>

int main(){
  std::vector<char> buff(MAX_PATH+1);
  ::GetCurrentDirectory(MAX_PATH+1, &buff[0]);
  std::string path(buff.begin(), buff.end());
}

Example on Ideone.

like image 22
Xeo Avatar answered Oct 13 '22 07:10

Xeo