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

2017-08-11 10:48:06 +08:00
 northisland

看 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).

我不明白的有两点:

2801 次点击
所在节点    问与答
2 条回复
northisland
2017-08-11 11:05:32 +08:00
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
2017-08-11 13:42:57 +08:00
这个是 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

```

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

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

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

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

© 2021 V2EX