I’m going through Mr. Stroustrup’s "A Tour of C++" book. In section 9.3 String Views, the author gives the following example:
string cat(string_view sv1, string_view sv2)
{
string res(sv1.length()+sv2.length());
char *p = &res[0];
for (char c : sv1) // one way to copy
*p++ = c;
copy(sv2.begin(),sv2.end(),p); // another way
return res;
}
When I try to compile this function, I get following error as std::string class doesn’t provide any constructor which takes a single int parameter.
error: no matching function for call to 'std::__cxx11::basic_string<char>::basic_string(std::basic_string_view<char>::size_type)' 11 | string res(sv1.length()+sv2.length());
I checked the Errata for 2nd printing of A Tour of C++ but there is no mention of this issue.
Is this a bug in the example provide or else I’m missing something else?
>Solution :
Is this a bug in the example provide or else I’m missing something else?
Yes this is an errata in the book as std::string doesn’t have a constructor that has only one parameter of type int(or convertible to int).
Instead it has a constructor std::string::string(size_type, char) that can take a char as the second argument. In particular, from std::string:
fill (6) string (size_t n, char c);(6) fill constructor:
Fills the string withnconsecutive copies of characterc.
Thus to resolve the errata, we should pass a second argument as shown below:
string res(sv1.length()+sv2.length(), '\0');