When to use const and const reference in function args?

后端 未结 4 1248
无人共我
无人共我 2020-11-28 23:46

When writing a C++ function which has args that are being passed to it, from my understanding const should always be used if you can guarantuee that the object will not be c

4条回答
  •  迷失自我
    2020-11-28 23:53

    The questions are based on some incorrect assumptions, so not really meaningful.

    std::string does not model immutable string values. It models mutable values.

    There is no such thing as a "const reference". There are references to const objects. The distinction is subtle but important.

    Top-level const for a function argument is only meaningful for a function implementation, not for a pure declaration (where it's disregarded by the compiler). It doesn't tell the caller anything. It's only a restriction on the implementation. E.g. int const is pretty much meaningless as argument type in a pure declaration of a function. However, the const in std::string const& is not top level.

    Passing by reference to const avoids inefficient copying of data. In general, for an argument passing data into a function, you pass small items (such as an int) by value, and potentially larger items by reference to const. In the machine code the reference to const may be optimized away or it may be implemented as a pointer. E.g., in 32-bit Windows an int is 4 bytes and a pointer is 4 bytes. So argument type int const& would not reduce data copying but could, with a simple-minded compiler, introduce an extra indirection, which means a slight inefficiency -- hence the small/large distinction.

    Cheers & hth.,

提交回复
热议问题