gpt4 book ai didi

c++ - 什么时候在函数中对 const 值使用 const 引用?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:18:51 25 4
gpt4 key购买 nike

在 64 位系统上,const& 是 8 个字节。对于小于 8 字节的值和对象,按值传递比按引用传递更有意义。即使是一个 8 字节的对象,复制也比传递引用然后访问该对象的成本更低。

在什么阈值下您应该更喜欢 const 引用而不是 const 值?

最佳答案

For values and objects smaller than 8 bytes, it makes sense to pass by value rather than reference. Even an 8 byte object is cheaper to copy than to pass the reference, then access the object.

引用不能保证作为指针实现。事实上,根据 §8.3.2/4:

It is unspecified whether or not a reference requires storage


At what threshold should you prefer a const reference over a const value?

情况很简单:

  • 当您只想读取值时使用const 引用
  • 使用 value 当您总是在函数内部复制对象时
  • 当你想修改函数内部的对象时使用reference

关于c++ - 什么时候在函数中对 const 值使用 const 引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22459167/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com