使用标量类型的"const"的好处?(例如"const double"或"const int")

q09*_*987 10 c++

///////////////////////////////////////
class A {
    ...
    const double funA(void)
    {...}
};

A a;
double x = a.funA(); 
// although the intention is to
// enforce the return value to be const and cannot be
// modified, it has little effect in the real world.

class A2 {
    ...
    double funB(void)
    {...}
};

///////////////////////////////////////
class A {
    void setA(const double d)
    { // now you cannot change the value of d, so what?
      // From my point of view, it is NOT a good practice to change the pass-in parameter
      // in this case, unless you want the caller to receive that change
      // instead, you can do 
      // const double dPassIn = d;
      / /then use dPassIn instead.
      ...
    }
};

class A2 {
    void setB(double d)
    {...}
};

//////////////////////////////////////
Run Code Online (Sandbox Code Playgroud)

从我的理解,我们应该更喜欢使用A2::funBA2::setB因为两者中使用的constA::funAA::setA没有什么意义.

//更新//

    FMOD_RESULT F_API EventSystem::getReverbPresetByIndex(const int index, 
                                FMOD_REVERB_PROPERTIES *props, char **name = 0);
Run Code Online (Sandbox Code Playgroud)

我认为FMOD是一个设计良好的包,它确实使用const int内部函数参数列表.现在,我同意A::setA(const double d)它的优势.

Pet*_*etr 7

按值返回时,常量无效,因为无论如何都无法强制执行.一些编译器发出警告.但是,将指针/引用返回到常量数据是有意义的.

将参数传递给函数时,最好(更安全,允许编译器优化)将其作为常量传递,除非您绝对需要更改数据.

  • 我会有一个非常非常小的答案来回答你的问题.如果按值返回对象,则将其设为const将阻止用户对该值调用非const方法.显然,用户总是可以将返回的值赋给非const值并在那里调用该方法.;)这几乎是我能想到的.我想如果const会阻止你做"if(foo()= 42)",但事实证明编译器实际上捕获了那个错误,因为返回不是l值. (2认同)