mercredi 27 novembre 2019

Why std::string does not have const char* cast (STL architecture question)?

I like to know pro's and con's for having and not-having such cast. At several places including here on Stackoverflow I can see that the const char* cast is considered bad idea but I am not sure why?

Lack of the (const char*) and forcing to always use c_str() cast creates some problems when writing generic routines and templates.

void CheckStr(const char* s)
{
}

int main()
{
    std::string s = "Hello World!";

    // all below will not compile with 
    // Error: No suitable conversion function from "std::string" to "const char *" exists!
    //CheckStr(s);             
    //CheckStr((const char*)s);  
    // strlen(s);

    // the only way that works
    CheckStr(s.c_str());
    size_t n = strlen(s.c_str());
    return 0;
}

For example, if I have a large number of text processing functions that accept const char* as input and I want to be able to use std::string each time I have to use c_str(). But in this way a template function can't be used for both std::string and const char* without additional efforts.

As a problem I can see some operator overloading issues but these are possible to solve.

Aucun commentaire:

Enregistrer un commentaire