From 3abc907bb4dab11f0eb7b050e2e15905807d190f Mon Sep 17 00:00:00 2001 From: dragonWater <42114817+cathaysia@users.noreply.github.com> Date: Wed, 3 Jun 2020 14:19:41 +0800 Subject: [PATCH] book: fix incorrect string literal (#102) and a typo (#103) --- book/en-us/03-runtime.md | 18 +++++++++++++++++- book/zh-cn/03-runtime.md | 18 +++++++++++++++++- 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/book/en-us/03-runtime.md b/book/en-us/03-runtime.md index 5ceee68..96e0989 100644 --- a/book/en-us/03-runtime.md +++ b/book/en-us/03-runtime.md @@ -260,6 +260,22 @@ Temporary variables returned by non-references, temporary variables generated by operation expressions, original literals, and Lambda expressions are all pure rvalue values. +Note that a string literal became rvalue in a class, and remains an lvalue in other cases (e.g., in a function): + +```cpp +class Foo { + const char*&& right = "this is a rvalue"; +public: + void bar() { + right = "still rvalue"; // the string literal is a rvalue + } +}; + +int main() { + const char* const &left = "this is an lvalue"; // the string literal is an lvalue +} +``` + **xvalue, expiring value** is the concept proposed by C++11 to introduce rvalue references (so in traditional C++, pure rvalue and rvalue are the same concept), a value that is destroyed but can be moved. @@ -617,4 +633,4 @@ Lambda expression ## Licenses -Creative Commons License
This work was written by [Ou Changkun](https://changkun.de) and licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. The code of this repository is open sourced under the [MIT license](../../LICENSE). \ No newline at end of file +Creative Commons License
This work was written by [Ou Changkun](https://changkun.de) and licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. The code of this repository is open sourced under the [MIT license](../../LICENSE). diff --git a/book/zh-cn/03-runtime.md b/book/zh-cn/03-runtime.md index 84592d8..023b6ef 100644 --- a/book/zh-cn/03-runtime.md +++ b/book/zh-cn/03-runtime.md @@ -225,6 +225,22 @@ int main() { 要么是求值结果相当于字面量或匿名临时对象,例如 `1+2`。非引用返回的临时变量、运算表达式产生的临时变量、 原始字面量、Lambda 表达式都属于纯右值。 +需要注意的是,字符串字面量只有在类中才是右值,当其位于普通函数中是左值。例如: + +```cpp +class Foo { + const char*&& right = "this is a rvalue"; // 此处字符串字面量为右值 +public: + void bar() { + right = "still rvalue"; // 此处字符串字面量为右值 + } +}; + +int main() { + const char* const &left = "this is an lvalue"; // 此处字符串字面量为左值 +} +``` + **将亡值(xvalue, expiring value)**,是 C++11 为了引入右值引用而提出的概念(因此在传统 C++中, 纯右值和右值是同一个概念),也就是即将被销毁、却能够被移动的值。 @@ -252,7 +268,7 @@ std::vector v = foo(); ### 右值引用和左值引用 -需要拿到一个将亡值,就需要用到右值引用的申明:`T &&`,其中 `T` 是类型。 +要拿到一个将亡值,就需要用到右值引用:`T &&`,其中 `T` 是类型。 右值引用的声明让这个临时值的生命周期得以延长、只要变量还活着,那么将亡值将继续存活。 C++11 提供了 `std::move` 这个方法将左值参数无条件的转换为右值,