Benefits of using “const” with scalar type? (e.g. “const double” or “const int”)

后端 未结 4 1667
[愿得一人]
[愿得一人] 2021-01-02 03:55
///////////////////////////////////////
class A {
    ...
    const double funA(void)
    {...}
};

A a;
double x = a.funA(); 
// although the intention is to
// enf         


        
4条回答
  •  北荒
    北荒 (楼主)
    2021-01-02 04:30

    When returning by value the constant has no effect as it cannot be enforced anyway. Some compilers issue a warning. However it DOES make sense to return a pointer/reference to constant data.

    When passing an argument into a function it is preferable (safer, allows for compiler optimizations) to pass it as a constant unless you absolutely need to change the data.

提交回复
热议问题