C ++ constructors and implicit string conversion

In C ++, I can write a class with a constructor that takes a parameter std::string. This will allow me to instantiate this class from std::stringor char *due to implicit conversions.

Is there a reason to have a constructor std::stringand constructor char *?

class MyStringClass {
 public:
    MyStringClass( const std::string &str ); // char * could implicitly use this constructor
    MyStringClass( const char * str );       // would this ever be necessary?
};

This question also applies to function arguments.

void do_stuff_with_string( const std::string &str );
void do_stuff_with_string( const char * str );

Edit:

To clarify, I'm interested in learning about performance. Let's say that these constructors / functions are called in api, which only accept char *. Should I have two separate functions to avoid building std::stringif I don't need to?

void do_stuff_with_string( const std::string &str )
{
    do_stuff_with_string( str.c_str() );
}

void do_stuff_with_string( const char * str )
{
    // call some api that only accepts char *
}
+4
2

, - C- std::string.

MyStringClass::MyStringClass( const std::string &str )
{
    // Do std::string-specific stuff here.
}

MyStringClass::MyStringClass(const char * str )
{
    // Do char* specific stuff here.
}

, const char * C- , , . .

:

#include <iostream>

int DoStuff(const std::string &myString)
{
    std::cout << myString << std::endl;
}

int main()
{
    DoStuff("This is a null terminated c-string");  // Fine!

    char charArray[] = { 'A', 'B', 'C' };           // Not null terminated!
    DoStuff(charArray);                             // Uh oh!
}

, . !

, , - , std::string(const char * const) c- . , . .

, ++ std::string::c_str(), C- . char* std::string -. .

+2

, , , char * . .

0

Source: https://habr.com/ru/post/1543460/


All Articles