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

Given static const char * const x = "test";

and a function with a signature void DoSomething(std::string && value)

, why is it legal to bind this value to a parameter like DoSomething(x);

?

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

When a function with an rvalue reference parameter expects to take responsibility for the parameter data, how does this deal with memory only in the read segments, for example in a PE file? I understand that the memory is not physically moved, but it looks like it will cause problems.

+3


source to share


1 answer


std::string

different from const char *

. When you initialize a reference with a different type of expression that it cannot directly bind to, a temporary structure is created that is of the correct reference type. The temporary is initialized by the initializer, and the link is bound directly to the temporary. Rvalue references can bind to temporary.



The function can then own the temporary data. The string literal is not modified (since the constructor string::string(const char *)

does not modify the literal and instead takes a copy of its contents).

+3


source







All Articles