[英]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";
给定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);
以及带有签名void DoSomething(std::string && value)
的函数,为什么将此左值绑定到参数是合法的,就像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. 我的印象是字符串文字是一个char数组,但是它会衰减为指针类型,并且仍然是左值。 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? 当带有右值引用参数的函数希望获得该参数数据的所有权时,这如何与PE文件的只读段中的内存一起使用? I understand the memory isn't physically moved, but it seems like this would cause problems. 我了解内存并未物理移动,但似乎会引起问题。
std::string
is different to const char *
. std::string
与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). 字符串文字不变(因为构造函数string::string(const char *)
不会更改文字,而是获取其内容的副本)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.