Should we generally use const_cast to make a function const?

Which is preferred?
1
2
3
4
class A {
	int num;
	A* foo() {return this;}
};

or
1
2
3
4
class A {
	int num;
	A* foo() const {return const_cast<A*>(this);}
};


The latter is more const correct of course, but is also messier in code (perhaps less efficient too?). Should we do this in general to make functions more const correct? Same goes with making pointer parameters const and such? Throwing const_cast here and there?

1
2
3
4
5
6
class A {
	int num;
	std::list<A*> a_list;
	A* foo() const {return const_cast<A*>(this);}
	void goo (const A* a) {a_list.push_back (const_cast<A*>(a));}
};

What a mess.
Last edited on
The latter is not at all const correct.

1
2
3
class A {
    const A* foo() const { return this; }
};
Topic archived. No new replies allowed.