V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
northisland
V2EX  ›  问与答

谁来解释一下, C++里双引用号,是个啥东西?

  •  
  •   northisland · Aug 11, 2017 · 3364 views
    This topic created in 3187 days ago, the information mentioned may be changed or developed.

    看 shared_ptr 里 operator=的解释,

    第二条,

    move (2)

    shared_ptr& operator= (shared_ptr&& x) noexcept;
    

    解释:

    The move assignments (2) transfer ownership from x to the shared_ptr object without altering the use_count. x becomes an empty shared_ptr (as if default-constructed).

    我不明白的有两点:

    • 双引用号是什么?

    • move(2) 表达的是什么情况?我能想象到的情景就是 share_ptr<int> ptr_i = shared_ptr<int>(new int) 这种情况,后面的是 x,这句过后就没了。

    northisland
        1
    northisland  
    OP
       Aug 11, 2017
    https://stackoverflow.com/questions/5481539/what-does-t-double-ampersand-mean-in-c11
    貌似这个讨论讲的是这个问题,但我还是看不懂。

    维基百科解释
    R-value:
    In computer science, a value considered independently of its storage location
    (独立于内存的值,就像你不能操作 i++这个数)

    L-value:
    In computer science, a value that points to a storage location, potentially allowing new values to be assigned
    (你可以操作++i 这个数,因为这个数就是 i 本身)
    manifold
        2
    manifold  
       Aug 11, 2017   ❤️ 1
    这个是 rvalue reference,因为对于 lvalue C++函数传值、返回是用 copy constructor,如果使用了 rvalue reference 可以使用 move constructor,减少 overhead。

    ```
    // MyClass has large overhead for copy ctor, but small overhead for move ctor
    MyClass x;
    // declaration
    void foo(MyClass x);
    void bar(MyClass&& x);

    foo(x); // use copy ctor
    bar(std::move(x)); // use move ctor

    ```
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   863 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 18:49 · PVG 02:49 · LAX 11:49 · JFK 14:49
    ♥ Do have faith in what you're doing.