For defining a second const version of a function, is it guaranteed safe to do this? It looks like it would have infinite recursion as I want to return const but the other function which I mean to call is non-const.
It works with g++ but I worry that this is unsafe.
#include <iostream>
using namespace std;
class test {
public:
int* doSomething(int a) {
int* someInt = new int(a);
return someInt;
}
const int* doSomething(int a) const {
return doSomething(a);
}
};
int main() {
test a;
cout << *a.doSomething(12345) << endl;
return 1;
}
Not quite: as @Pete Becker has pointed out in the comments, if you had called the
constversion that will recurse:When providing
constand non-constversions of a function that requires duplicated code, it's best to implement theconstversion, then have the non-constversion call it in a specific way.From Scott Myers Effective C++ - Third Edition:
Scott Myers goes on to provide a safe means for doing this:
In the non-
constversion, there are two casts: thestatic_castbasically turnsthisintoconst this, where theconst_castcasts away theconst-ness of the return. This is safe to do, because to call the non-constversion, you must've had a non-const this.However, if you are just providing access to a member, it's simple and easier to read to just have the following: