Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Const Methods that Return References

Tags:

class Foo
{
    int Bar;

    public:

    int& GetBar() const
    {
        return Bar;
    }
}

Is it okay that GetBar is a const method? It's not actually changing anything, but it's providing the "outside world" with a means of changing it.

like image 770
Maxpm Avatar asked Feb 10 '11 12:02

Maxpm


People also ask

Can references be const?

The grammar doesn't allow you to declare a “const reference” because a reference is inherently const . Once you bind a reference to refer to an object, you cannot bind it to refer to a different object.

Does const reference copy?

Not just a copy; it is also a const copy. So you cannot modify it, invoke any non-const members from it, or pass it as a non-const parameter to any function. If you want a modifiable copy, lose the const decl on protos .

Can const function return value?

The reason const has no meaning when you're returning a built-in type by value is that the compiler already prevents it from being an lvalue (because it's always a value, and not a variable). Only when you're returning objects of user-defined types by value does it become an issue.


2 Answers

You have a typo in your code, this is what you probably meant:

class Foo
{
    int Bar;

    public:

    int& GetBar() const
    {
        return Bar; // Removed the ampersand, because a reference is returned, not an address
    }
}

And no, this is not legal. When tagging a method with const, not only are you promising you won't touch any of the internal state of the object, you also promise that you will not return anything that can be used to change the state of the object. A non-const reference may be used to modify the value of Bar outside the scope of GetBar(), hence you are implying that you cannot hold the promise.

You must either change the method to being non-const, return a const reference, or make Bar exempt of the promise by marking it as mutable. E.g.: mutable int Bar; The mutable keyword tells the compiler that the logical constness of the object does not depend on the state of Bar. Then you are allowed to do whatever you please with it.

like image 128
Jörgen Sigvardsson Avatar answered Sep 29 '22 07:09

Jörgen Sigvardsson


Nope, since you cant do the following assignment: const int x; int &y = x;

What you can do though is const int x; const int &y = x;

And of course there is no problem in overloading the method and creating both const and non-const variants.

like image 35
Šimon Tóth Avatar answered Sep 29 '22 07:09

Šimon Tóth