简体   繁体   English

当字符串文字作为const字符串传递给函数时会发生什么?

[英]What happens when a string literal passed as const string& to a function?

Here is an example from the C++ Primer : A function count() declared as: 以下是C ++ Primer中的一个示例:函数count()声明为:

int count(const string & a, char b);

and called: 并呼吁:

count("abcde", 'a')

It works. 有用。 Here "abcde" is a string literal and passed to count() as const string & . 这里"abcde"是一个字符串文字,并作为const string &传递给count()

But at the same time this code 但同时这段代码

string & s="abcde";

was wrong simply because we cannot assign a string literal to a string & . 之所以错,只是因为我们无法将string文字分配给string &

So what happened when "abcde" was passed to count() ? 那么当"abcde"传递给count()什么? Is there something like a temporary string be initialized by "abcde" and then passed to count() ? 是否有类似临时字符串的东西由"abcde"初始化然后传递给count()

Is there something like a temporary string be initialized by "abcde" and then passed to count() ? 是否有类似临时字符串的东西由"abcde"初始化然后传递给count()

Yes, that's exactly what happens there. 是的,那就是那里发生的事情。

A temporary instance of std::string is constructed using the implicit constructor (5) 使用隐式构造函数(5)构造std::string临时实例

 basic_string( const CharT* s,
               const Allocator& alloc = Allocator() );

and passed as rvalue reference to the function. 并作为rvalue引用传递给函数。


As for your second sample this would work with a const reference as well: 至于你的第二个例子,这也适用于const引用:

const std::string& s = "abcde";

see demo 看看演示

The point is a lvalue reference can't be initialized from a rvalue. 该点是左值参考不能从右值初始化。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 C++ 中将字符串文字传递给接受 const std::string & 的函数时会发生什么? - What happens when a string literal is passed to a function accepting a const std::string & in C++? c ++传递字符串文字而不是const std :: string&? - c++ passing a string literal instead of a const std::string&? 什么时候使用const string&与const string比较好 - When is it better to use const string& versus const string 从C ++的构造函数中向成员const char *变量分配字符串文字时会发生什么? - What happens when assigning a string literal to a member const char* variable from within a constructor in C++? 使用const std :: string&作为方法参数类型时,处理nullptr const char *的正确方法是什么? - What is the correct way to handle nullptr const char* when using const std::string& as method argument type? 将字符串文字传递给一个带有std :: string&的函数 - passing a string literal to a function that takes a std::string& 是否可以将字符串文字传递给采用const char *的函数? - Can a string literal be passed to a function that takes const char*? 取消引用集合迭代器时,将“ string&”绑定到“ const string”时出错 - Error binding 'string&' to 'const string' when dereferencing a set iterator 何时以及为什么应该使用 String&、String 和 Const? - When and why should you use String&, String and Const? 当作为参数传递给C ++中的函数时,const string&str和string const&str和有什么区别? - What is the difference between const string & str and string const & str when passed as an argument to a function in c++
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM