A fixed length string class with char* conversion operator

Question | Jan 13, 2017 | nextptr 

A fixed length string class uses a fixed length char array (char[]) for storage. As compared to dynamically allocated string (std::string) a fixed length string is inflexible, but has performance advantages because:

  • The fixed length string data is allocated on stack if the string object itself is created on stack, which is much faster than heap allocation
  • If the fixed length string objects are stored in an STL container (e.g std::vector), the memory allocation is contiguous

Here is a minimal example of a fixed length string - FixedString - that defines an implicit constructor and a const char* conversion operator:

template<size_t S>
class FixedString {
public:

 FixedString(const char* s=nullptr) {
   // set first and last bytes to null ('\0')
   str_[0] = str_[S] = 0; 
   if( s )
    ::strncpy(str_, s, sizeof str_ - 1);
 }

 // conversion operator
 operator const char* () { 
   return str_; 
 }

private:
 // keep an extra char for null
 char str_[S + 1]; 
};

Look at the following use of FixedString and select what would be the output:

FixedString<4> s1("Hey");
const char* cool = "Cool";
s1 = cool;
std::cout << s1 << " ";
std::cout << (s1 ? "True " : "False ");
std::cout << (s1 == cool ? "True " : "False ");
std::cout << (strcmp(s1,cool) == 0 ? "True " : "False ");