2

重複の可能性:
明確にするために、戻り型に役に立たない型修飾子を使用する必要がありますか?

値で返すこととconst値を返すことについて混乱しています。たとえば、関数が実行されると、すべてのローカルはスコープ外になります。したがって、関数から値を返す場合は、参照による戻りでない限り、コピーによるパスである必要があります。したがって、これが発生すると、関数は後で変更できるコピーを返します。したがって、ローカル変数がconstと宣言されていても、別の変数でそれを読み取り、後者を簡単に変更できます。

const int DoubleValue(int nX)
{
    int nValue = nX * 2;
    return nValue; // A copy of nValue will be returned here
} // n

constここで何を意味するのか理解するのに混乱しています。nValue関数本体にconstはありますか?のように割り当てを行うと、z = DoubleValue(x);明らかに変更できzます。

どのような状況下で恒常性が強制されますか?オブジェクトDoubleValue(x)はconstオブジェクトですか?それは何を表していますか?

4

1 に答える 1

7

There is a corner case where you returning a const value will make a difference. If I remember correctly from one of Scott Meyers' books, if you overload an operator (say +) and you return a value that is not const you could do something like:

A + B = C;

Which is not something you want to allow. The following code compiles (but if you replace A by const A in the operator it won't):

#include <iostream>

class A
{
public:
    A(int i): i_(i) {}
    A operator +(A& rhs) { return A(i_ + rhs.i_); }

private:
    int i_;
};

int main(int argc, char* argv[])
{
    A a(1);
    A b(2);
    A c(3);

    a + b = c;

    return 0;
}
于 2012-09-12T02:18:49.620 に答える