C++ 常量右值有没有啥意义?

2020-09-15 00:29:37 +08:00
 by73

例如 void f(const T&& val) 这样的常量右值,虽然编译能通过,但总觉得语义上怪怪的,就想问问这种写法到底有没有意义,还是只是单纯的因为 reference collapsing 所以才保留这种写法?

(日常水,轻喷。。

2896 次点击
所在节点    C++
7 条回复
dangyuluo
2020-09-15 01:15:23 +08:00
The semantics of getting a const rvalue reference (and not for =delete) is for saying:

1. we do not support the operation for lvalues!
2. even though, we still copy, because we can't move the passed resource, or because there is no actual meaning for "moving" it.

真纠结
amosasas
2020-09-15 09:37:33 +08:00
@dangyuluo C++的日常...
Wirbelwind
2020-09-15 19:15:15 +08:00
没什么意义,有时候可以阻止重载
by73
2020-09-23 00:27:22 +08:00
@dangyuluo 顺着你这个引用我找到了稍微有点意义的例子:

int* const ptr = new int(9);
auto p = std::unique_ptr<int> { std::move(ptr) };

来源: https://stackoverflow.com/a/60587511

只能勉强接受这个解释了,虽然还是有点理解不能😂
by73
2020-09-23 00:29:07 +08:00
@amosasas 还是不纠结了,似乎意义不大。。只是凑巧在 folly::futures 里的测试用例看到这个东西,有点好奇
Sinksky
2020-10-18 00:25:01 +08:00
@by73 《深入理解 C++11 》
![0O0v1U.png]( https://s1.ax1x.com/2020/10/18/0O0v1U.png)
by73
2020-10-21 00:52:43 +08:00
@Sinksky “我们还没有看到常量右值引用有何用处”😂不过 1L 举得例子里说明了标准库中可能有用到,也就是为了阻止重载,不过语义上的确没有啥含义

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/707016

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX