简体   繁体   中英

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:

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 & .

But at the same time this code

string & s="abcde";

was wrong simply because we cannot assign a string literal to a string & .

So what happened when "abcde" was passed to count() ? Is there something like a temporary string be initialized by "abcde" and then passed to count() ?

Is there something like a temporary string be initialized by "abcde" and then passed to count() ?

Yes, that's exactly what happens there.

A temporary instance of std::string is constructed using the implicit constructor (5)

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

and passed as rvalue reference to the function.


As for your second sample this would work with a const reference as well:

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

see demo

The point is a lvalue reference can't be initialized from a rvalue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM