by73
V2EX  ›  C++

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

  •  
  •   by73 ·
    plxty · Sep 15, 2020 · 3662 views
    This topic created in 2089 days ago, the information mentioned may be changed or developed.

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

    (日常水,轻喷。。

    7 replies    2020-10-21 00:52:43 +08:00
    dangyuluo
        1
    dangyuluo  
       Sep 15, 2020
    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
        2
    amosasas  
       Sep 15, 2020
    @dangyuluo C++的日常...
    Wirbelwind
        3
    Wirbelwind  
       Sep 15, 2020
    没什么意义,有时候可以阻止重载
    by73
        4
    by73  
    OP
       Sep 23, 2020
    @dangyuluo 顺着你这个引用我找到了稍微有点意义的例子:

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

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

    只能勉强接受这个解释了,虽然还是有点理解不能😂
    by73
        5
    by73  
    OP
       Sep 23, 2020
    @amosasas 还是不纠结了,似乎意义不大。。只是凑巧在 folly::futures 里的测试用例看到这个东西,有点好奇
    Sinksky
        6
    Sinksky  
       Oct 18, 2020
    @by73 《深入理解 C++11 》
    ![0O0v1U.png]( https://s1.ax1x.com/2020/10/18/0O0v1U.png)
    by73
        7
    by73  
    OP
       Oct 21, 2020
    @Sinksky “我们还没有看到常量右值引用有何用处”😂不过 1L 举得例子里说明了标准库中可能有用到,也就是为了阻止重载,不过语义上的确没有啥含义
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   4219 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 51ms · UTC 00:59 · PVG 08:59 · LAX 17:59 · JFK 20:59
    ♥ Do have faith in what you're doing.