USING STD::STRING

Asked By 0 points N/A Posted on -
qa-featured

I was using std::string as a buffer and one of my friend noticed and said there are downsides of using std::string. If this is so then what is the problem in using std::string?

SHARE
Answered By 0 points N/A #318438

USING STD::STRING

qa-featured

It is not recommended to use std :: string as a buffer (listed in any order) for various reasons:

• std :: string was not meant to be used as a buffer. You will have to re-examine the description of the class to make sure that no “trap” prevents certain modes of use (or does not trigger undefined behavior).

• In particular: Before C ++ 17, you can not even write via the pointer you get with data () – it’s const Tchar *; Your code would therefore cause undefined behavior. (But & (str [0]), & (str.front ()) or & (* (str.begin ())) would work.)

• The use of std :: string for buffers is confusing for implementation readers, which assume that you would use std :: string for strings.

• Worse, it’s confusing for anyone who uses this feature. They may also believe that the return is a chain, i. H. To obtain a valid text, readable by the man.

• std :: unique_ptr would be fine for your case or even std :: vector. In C ++ 17, you can also use std :: byte for the element type. A more sophisticated option is a class with SSO-like functionality, for example. Boost’s small_vector (thanks, @ gast128, for the mention).

• (Minor point 🙂 libstdc ++ had to change its ABI for std :: string to match the C ++ 11 standard. In some cases (which are unlikely at present), link or run problems may not occur with another type for your buffer.

Login/Register to Answer

Related Questions