2

I often see the following structure, especially in constructors:

class::class(const string &filename)
{
}


class::class(const char * const filename)
{
}

By step-by-step debug, I found out the 2nd constructor is always called if I pass a hard-coded string.

Any idea:

1) Why the dual structure is used?

2) What is the speed difference?

Thanks.

4

4 回答 4

3

需要两个构造函数,因为您可以将 a 传递NULL给您的MyClass::MyClass(const std::string &arg). 提供第二个构造函数可以使您免于愚蠢的崩溃。

例如,您为您的类编写构造函数,并使其采用 a const std::string &,这样您就不必检查任何指针是否有效,如果您要使用const char*. 在您的代码中的任何地方,您都只是在使用std::strings. 在某些时候,您(或其他程序员)会通过const char*. 这是一个很好的部分std::string- 它有一个构造函数,它接受char*,这非常好,除了std::string a_string(NULL)编译没有任何问题,只是不起作用。

这就是您展示的第二个构造函数派上用场的地方:

MyClass::MyClass(const char* arg)
    : m_string(arg ? arg : "")
{}

std::string如果你将它传递给它,它将成为一个有效的对象NULL

在这种情况下,我认为您无需担心任何速度。您可以尝试测量,尽管我担心您会对差异很小(如果有的话)感到惊讶。

编辑:刚刚试过std::string a_string(NULL);,编译得很好,这就是它在我的机器上运行时发生的情况(OS X + gcc 4.2.1)(我记得我前段时间在 Windows 上试过,结果非常相似,如果不完全相同的话):

std::logic_error: basic_string::_S_construct NULL not valid

于 2010-01-29T23:41:09.807 回答
1

如果实现自己处理 s ,这很有用const char*,但主要由std::string用户调用。这些可以使用std::stringAPI 调用,通常只是调用c_str()和分派到const char*实现。另一方面,如果调用者已经有一个 c 字符串,则不需要std::string构造临时或不需要的字符串(这可能会很昂贵,对于更长的字符串,它是一个堆分配)。

另外,我曾经用它来解决以下情况:

我的接口采用std::string's,但必须在外部模块中实现,因此模块和调用者模块的 STL 二进制版本必须完全匹配,否则它会崩溃(对于可移植库来说不是很好......)。所以我将实际接口更改为 use const char*,并添加std::string了我声明的重载inline,因此它们没有被导出。它没有破坏现有代码,但解决了我所有的模块边界问题。

于 2010-01-29T22:34:46.877 回答
0

1) Why the dual structure is used?

The string reference version is required if std::string objects are to be used conveniently as parametersm as there is no implicit conversion from a std::string to a const char const. The const char * const version is optional, as character arrays can implicitly be converted into std::strings, but it is more efficient, as no temporary std::string need be created.

2) What is the speed difference?

You will need to measure that yourself.

于 2010-01-29T22:32:44.413 回答
0

它们基本上是为了方便而提供的。有时,如果你调用 C 函数,你会得到 char* 指针。其他的,你得到字符串,所以提供这两个构造函数只是对调用者的一种方便。至于速度,两者的速度几乎相同,因为它们都向构造函数发送内存地址。

于 2010-01-29T22:34:31.777 回答