C++ const modifier with primitive types

后端 未结 5 2067
死守一世寂寞
死守一世寂寞 2020-12-31 12:16

Should I pay attention on const modifier working with primitive types? Which one is more syntactically correct and why?

First version:

f         


        
5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-31 12:56

    I am going to say that with primitives it may well be more efficient to actually copy them. When you pass a reference, the compiler still has to pass bytes on the stack, and then has to dereference the address to get the content.

    In addition, passing by value overcomes any possible concurrency / volatility issues regarding the memory of what is being passed.

    It's a case of "don't try to optimise here".

    Returning by const is style. I usually don't, others prefer to just in case someone is gonig to do something with the returned value. Next you'll find people returning them by r-value reference...

    I would normally go for your first option. The other alternative is pass by value (not necessary to use const) and return by const value.

提交回复
热议问题