2

Suppose I have some class X which I return from a method:

class A
{
    X GetValue();
    void SetValue(X x);

    // X& GetValue(); // old code
private:
    X x;
};

In the past I used to return by reference instead of using setters and getters, but I've opted for the latter because the class is so small, so now my code might have occurrences of this kind of thing happening:

instanceOfA.GetValue() = something;

This is ofcourse complete nonsense now, and I want to disallow it. What can I do to prevent X being assigned to in this way? I thought about returning const X from my GetValue() method, but I'm told that doing this is obsolete.

Community
  • 1
  • 1
quant
  • 21,507
  • 32
  • 115
  • 211
  • Given that no sane programmer would write code that uses your example and expects it to do something after reading the signature of `A::GetValue`, perhaps you're simply better off just purging that usage from the code that exists to discourage this without explicitly forbidding it. – Wug Apr 29 '15 at 04:45
  • You can't , but don't worry about it. If people want to do silly things that's their problem. – M.M Apr 29 '15 at 04:47
  • Have you tried that? I check it is already disallowed by the compiler: `error: lvalue required as left operand of assignment`. – tivn Apr 29 '15 at 05:59

0 Answers0