Const: is that legit?

Started by
5 comments, last by Zipster 14 years, 1 month ago
T & get() { return T; }
T get() const { return T; }

That is, overloading a function for both const and non-const "this"?
Please point my english mistakes everytime you can.
Advertisement
Quote:Original post by WindScar
overloading a function for both const and non-const "this"?
Yes.
MyClass obj;const MyClass& constObj = obj;      MyClass* pObj = &obj;const MyClass* pConstObj = &obj;obj.get();//calls non const overloadpObj->get();//calls non const overloadconstObj.get();//calls const overloadpConstObj->get();//calls const overload

What's the deal with "const-overloading"?
Yay perfect. Thank you.
Please point my english mistakes everytime you can.
Just for reference, instead of returning by value from the const member function, why not return by const reference? Saves you from making a copy.

There are a few rare situations where this is actually undesirable, particularly related to multi-threaded code, but the majority of the time it's not a problem.
Quote:Original post by cache_hit
Just for reference, instead of returning by value from the const member function, why not return by const reference? Saves you from making a copy.

There are a few rare situations where this is actually undesirable, particularly related to multi-threaded code, but the majority of the time it's not a problem.


Also, speed-wise this will only gain you anything if T is a type that is expensive to copy. If it's just an int or a small POD struct, returning by const reference is probably not going to win you much (might even be slower that way).
It's unlikely that returning by const reference would ever be slower, as that code would always be inlined and become pretty much a no-op. The return-by-value version could legally be made a no-op as well due to copy constructor elision, but as far as I've seen, compilers are fairly timid about copy constructor elision except in RVO circumstances.
Another approach:

template<typename T>class Foo{    const T& getIt() const    {        // nasty code    }    T& getIT()    {        // don't have to rewrite nasty code        return const_cast<T&>(static_cast<const Foo&>(*this).getIt());    }};

Of course if you only have a return statement then this code is a lot uglier, but it's nice if you have a larger or more complicated block of code and don't want to write it multiple times.

This topic is closed to new replies.

Advertisement