【发布时间】:2012-04-11 15:44:25
【问题描述】:
我有几个问题,我认为对于具有 C++ 经验的人来说很容易回答,我会为 TL 加粗问题;DR
给定以下代码:
void stringTest(const std::string &s)
{
std::cout << s << std::endl;
}
int main()
{
stringTest("HelloWorld");
}
希望有人可以在这里指出我思考过程中的错误:
为什么 stringTest 中的参数在传递 C-Style 字符串时必须标记为 const? 使用其 cstyle 字符串构造函数是否会隐式转换为 std::string ,因此“s”不再是对文字的引用(并且不需要是 const)。
此外,cstyle 字符串构造函数是什么样的,以及编译器如何知道在看到时调用它:
stringTest("HelloWorld");
它是否简单地将字符串文字识别为 char* 之类的东西?
我在研究复制构造函数时偶然发现了这些问题。我自己澄清的另一个快速问题......
如果是这样的情况:
std::string s = "HelloWorld";
cstyle字符串构造函数是不是用来实例化一个临时std::string,然后用字符串拷贝构造函数把临时字符串复制到"s"中?:
std::string(const std::string&);
【问题讨论】:
-
"为什么 stringTest 中的参数必须标记为 const" — 无论何时必要,您都希望 所有 引用 @987654326 @ 实际上没有被修改。
-
@leftaroundabout:公平点,我一定会牢记这一点。