简体   繁体   中英

Why is a static const char * const variable bindable to an rvalue reference parameter when it is an lvalue?

Given static const char * const x = "test"; and a function with the signature void DoSomething(std::string && value) , why is it legal to bind this lvalue to the parameter like so DoSomething(x); ?

I was under the impression that the string literal is an array of char but it decays to the pointer type and is still an lvalue. I'm just confused why this is legal.

When the function with an rvalue reference parameter expects to take ownership of the parameter's data, how does this work with memory in read only segments of say a PE file? I understand the memory isn't physically moved, but it seems like this would cause problems.

std::string is different to const char * . When you initialize a reference with an expression of different type that it can't bind directly to, then a temporary is created which has the correct type for the reference. The temporary is initialized by the initializer provided, and the reference is bound directly to the temporary. Rvalue references can bind to temporaries.

The function could then take ownership of the temporary's data. The string literal is unchanged (because the constructor string::string(const char *) does not change the literal, and instead takes a copy of its content).

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