在C++中,我可以用一个构造函数编写一个类,该构造函数需要std::string
参数。由于隐式转换,这将允许我从std::string
或char *
构造此类的实例。C++构造函数和隐式字符串转换
是否曾有理由同时拥有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 *
。如果我不需要,有两个单独的功能来避免构建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 *
}
显而易见的原因是,如果你想以不同的方式处理它们。当然,还有其他原因,如果不简单地提供一个清单,就很难回答这个问题。你能给我们提供更多关于你想要做什么的信息吗? –
@CodyGray我想我更多地要求表现。是否值得同时避免构造一个字符串(如果在函数内部,我只使用.c_str()方法),或者开销如此之小,我不应该担心它? –
@CodyGray当你指出你自己保存的是一个字符串的构造。这种开销是否是“分钟”取决于你的程序中如何使用这个类很难在这里回答。 –