gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:10:07 24 4
gpt4 key购买 nike

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

是否有理由同时拥有 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?
};

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

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

编辑:

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

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 *
}

最佳答案

如果您希望以不同方式处理 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 * 的参数也有可能不是以 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!
}

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

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

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

关于C++ 构造函数和隐式字符串转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24067188/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com