C-Style字符串到std :: string转换澄清

Rik*_*ken 5 c++ string copy

我有几个问题,我认为对于有C++经验的人来说很容易回答,我会大胆提出TL的问题; DR

给出以下代码:

void stringTest(const std::string &s)
{
    std::cout << s << std::endl;
}

int main()
{
    stringTest("HelloWorld");
}
Run Code Online (Sandbox Code Playgroud)

希望有人可以在我的思考过程中指出错误:

为什么在传递C-Style字符串时stringTest中的参数必须标记为const?是不是存在使用其cstyle字符串构造函数发生的std :: string的隐式转换,因此"s"不再是对文字的引用(并且不需要是const).

此外,cstyle字符串构造函数看起来是什么样的,编译器如何知道在看到它时调用它:

stringTest("HelloWorld");
Run Code Online (Sandbox Code Playgroud)

它是否只是将字符串文字识别为char*?

在研究复制构造函数时,我偶然发现了这些问题.我自己澄清的另一个快速问题......

在类似的情况下:

std::string s = "HelloWorld";
Run Code Online (Sandbox Code Playgroud)

用于实例化临时std :: string的cstyle字符串构造函数,然后使用字符串复制构造函数将临时字符串复制到"s"中吗?:

std::string(const std::string&);
Run Code Online (Sandbox Code Playgroud)

Fre*_*Foo 2

为什么在传递 C 风格字符串时 stringTest 中的参数必须标记为 const?

仅当参数是引用时才必须这样做,因为临时对象std::string是根据char const*您传入的构造的,并且const对临时对象的非引用是非法的。

它只是将字符串文字识别为类似于 char* 的东西吗?

字符串文字是一个char const数组,它衰减为char const*。由此,编译器推断它应该使用非explicit构造函数std::string::string(char const *)来构造临时变量。

是否使用cstyle构造函数实例化临时std::string,然后使用字符串复制构造函数将临时字符串复制到“s”中?

实际情况比这要复杂一些。是的,创建了一个临时的。但复制构造函数可能会被调用,也可能不会被调用;作为一种优化,编译器可以跳过复制构造。不过,仍然必须提供复制构造函数,因此以下内容将无法编译:

class String {
    String(char const *) {}
  private:
    String(String const &);
};

int main()
{
    String s = "";
}
Run Code Online (Sandbox Code Playgroud)

此外,在 C++11 中,将使用移动构造函数(如果提供);在这种情况下,不需要复制构造函数。