Cppcoreguidelines: Is vector<char> necessary when we have string? (Reconcile SL.str.1 and SL.con.2)

Created on 18 Nov 2017  路  4Comments  路  Source: isocpp/CppCoreGuidelines

SL.con.2 recommends using a vector<char> instead of a string for a container of individual character. However SL.str.1 recommends using string for all character sequences.

I don't see an advantage using a vector in any way:

  • strings can do everything vectors can
  • strings have additional useful operations specifically for manipulating characters
  • the underlying data structure is a contiguous array in memory for both
  • mixing the two is impossible without boilerplate conversion functions

The only difference would be a very specific semantic one, and I don't think it's worth the hassle.

Most helpful comment

I see the difference now, thank you. I was confused by the term "character", as it was different from raw binary data in my mind. Shouldn't we use std::byte for this kind of data instead of unsigned char (SL.str.5) anyway ?

All 4 comments

Not all sequences of characters are strings, e.g. a sequence of binary data stored as char or unsigned char should be in vector<char> or vector<unsigned char> not std::string or std::basic_string<unsigned char> (binary data stored as bytes is not a textual string). SL.con.2 seems clear and correct. Maybe SL.str.1 could be clarified to say it is talking about _textual_ character sequences, so it is consistent with SL.con.2

I see the difference now, thank you. I was confused by the term "character", as it was different from raw binary data in my mind. Shouldn't we use std::byte for this kind of data instead of unsigned char (SL.str.5) anyway ?

std::byte is defined since C++17. I think it's one of reasons.
But std::byte is better in this case in my point of view

Thank you for the question. Per our editors' discussion and the discussion above, a vector<char> and string aren't exactly the same. For example, the vector could be an input buffer or a buffer used for storage during some iterative operation.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

vingeldal picture vingeldal  路  4Comments

imre-palik picture imre-palik  路  6Comments

galik picture galik  路  3Comments

rmasp98 picture rmasp98  路  7Comments

JVApen picture JVApen  路  4Comments