5

范围for语句里为什么要用引用?

 3 years ago
source link: https://www.zhihu.com/question/438300953/answer/1665978218
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

范围for语句里为什么要用引用?

在学c++过程中遇到个问题, 已经在vs2013里试过 for (auto c : test_string)cout << c <&…
8
1,482
登录一下,更多精彩内容等你发现
贡献精彩回答,参与评论互动
C++程序猿, 公众号:高级开发者

你说的对一半,对于 string 这种数据结构来说,其由基本数据结构char组成,对于 基础数据结构 来说,for应该用 非引用,避免间接取址。

也就是说 for (auto c : test_string) cout << c << endl; 比引用要有效。

那什么时候用引用呢?就是非基础数据结构的时候,例如大型结构体 sizeof(STRUCT) > sizeof(size_t),那时候用引用比值有效,避免拷贝,拷贝是有开销的。

在不改变元素的情况下,最终效果是一样的,只不过哪种写法 更高效 罢了;否则通过引用来改写元素而不是拷贝。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK