std::string s1 {"Modern C++", 3} vs std::string s1 {str, 3}
Solution 1:
From:
https://en.cppreference.com/w/cpp/string/basic_string/basic_string
std::string s1 {"Modern C++", 3};
Uses the following constructor:
basic_string( const CharT* s,
size_type count,
const Allocator& alloc = Allocator() );
So takes 3 chars to get Mod
.
std::string s2 {str, 3};
will use the following constructor:
basic_string( const basic_string& other,
size_type pos,
const Allocator& alloc = Allocator() );
So taking the string from position 3 onwards giving : ern C++
.
Solution 2:
One is calling string(char const*, count)
, the other string(string const&, pos)
.
One gets the first 3 characters from a buffer, the other all the characters after the 3rd one.
This is because C++ has raw character buffers and std strings. "this is not a std::string"
. "this is a std string"s
, std::string so_is="this";
.
std::string
is more than 30 years old, and it was added to the C++ language without sufficient care (unlike the STL, which went through more iterations before being added).
Its interface is honestly too rich, and you can run into stuff like this; multiple overloads that lead to confusing results.