Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Error in the example code of A Tour of C++

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 with n consecutive copies of character c.


Thus to resolve the errata, we should pass a second argument as shown below:

string res(sv1.length()+sv2.length(), '\0');
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading