C++ 构造函数和隐式字符串转换

Bri*_*ker 6 c++ string class function implicit-conversion

在 C++ 中,我可以编写一个带有带std::string参数的构造函数的类。由于隐式转换,这将允许我从std::string或构造此类的实例char *

有没有理由同时拥有std::string构造函数和char *构造函数?

class MyStringClass {
 public:
    MyStringClass( const std::string &str ); // char *'s could implicitly use this constructor
    MyStringClass( const char * str );       // would this ever be necessary?
};
Run Code Online (Sandbox Code Playgroud)

这个问题也适用于函数参数。

void do_stuff_with_string( const std::string &str );
void do_stuff_with_string( const char * str );
Run Code Online (Sandbox Code Playgroud)

编辑:

澄清一下,我想知道更多关于性能的信息。假设这些构造函数/函数正在调用只接受char *. std::string如果我不需要,有两个单独的函数来避免构造 a是否值得?

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 *
}
Run Code Online (Sandbox Code Playgroud)

Kar*_*oll 3

如果您希望处理 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.
}
Run Code Online (Sandbox Code Playgroud)

还有一种可能性是, 的参数const char *不是一个以 null 结尾的 C 字符串,而实际上是一个指向单个字符的指针,或者一个非 null 结尾的字符数组。在这种情况下,隐式转换可能会失败。

例子:

#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!
}
Run Code Online (Sandbox Code Playgroud)

上面的示例适用于函数,但同样也可以应用于构造函数。上面的例子编译时没有警告!

就性能而言,由于std::string(const char * const)构造函数会将 c 字符串复制到它自己的内部缓冲区中,因此肯定会受到影响。然而,在大多数情况下,影响可以忽略不计,因为复制非常有效。然而,对于非常大的字符串,这可能是一个问题。

但作为一般规则,请尝试尽可能多地使用 C++ 字符串,并std::string::c_str()在需要 C 样式字符串时使用成员。在大多数情况下,偶尔从char*to进行字符串复制std::string将是一个微优化。只有在对性能非常关键的代码中,这才是一个潜在的问题。