Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you handle strings in C++?

Tags:

c++

string

Which is your favorite way to go with strings in C++? A C-style array of chars? Or wchar_t? CString, std::basic_string, std::string, BSTR or CComBSTR?

Certainly each of these has its own area of application, but anyway, which is your favorite and why?

like image 653
Ra. Avatar asked Sep 25 '08 13:09

Ra.


2 Answers

std::string or std::wstring, depending on your needs. Why?

  • They're standard
  • They're portable
  • They can handle I18N
  • They have performance guarantees (as per the standard)
  • Protected against buffer overflows and similar attacks
  • Are easily converted to other types as needed
  • Are nicely templated, giving you a wide variety of options while reducing code bloat and improving performance. Really. Compilers that can't handle templates are long gone now.

A C-style array of chars is just asking for trouble. You'll still need to deal with them on occasion (and that's what std::string.c_str() is for), but, honestly -- one of the biggest dangers in C is programmers doing Bad Things with char* and winding up with buffer overflows. Just don't do it.

An array of wchar__t is the same thing, just bigger.

CString, BSTR, and CComBSTR are not standard and not portable. Avoid them unless absolutely forced. Optimally, just convert a std::string/std::wstring to them when needed, which shouldn't be very expensive.

Note that std::string is just a child of std::basic_string, but you're still better off using std::string unless you have a really good reason not to. Really Good. Let the compiler take care of the optimization in this situation.

like image 160
Zathrus Avatar answered Oct 28 '22 06:10

Zathrus


std::string !!

There's a reason why they call it a "Standard".

basic_string is an implementation detail and should be ignored.

BSTR & CComBSTR only for interOp with COM, and only for the moment of interop.

like image 29
James Curran Avatar answered Oct 28 '22 07:10

James Curran