C++ Core Language Clarification

Overloaded operator->

Specify exactly when the return-type of an overloaded operator-> is checked for validity; specifically, at the point of use, not declaration.

The section in the ARM (section 13.4.6, p. 337) regarding overloading operator-> states:
An expression x->m is interpreted as (x.operator->())->m for a class object x. It follows that operator->() must return either a pointer to a class or an object or or a reference to a class for which operator->() is defined.
This is perfectly valid; however, it doesn't specify when the check of the return-type is to be performed. Most, if not all, compilers check the return-type at the point of the declaration of the overloaded operator->. When using templates, this is too soon and should be deferred until an actual point of use.

For template classes that have "smart-pointer"-like functionality, operator-> is often overloaded something like this:
	template< class T > class pointer {
		T *object;
		// ...
		T& operator* () { return *object; }
		T* operator->() { return  object; }	// line 7
However, if we have a pointer<int>, i.e., parameterized with a non-class, such as:
	main() {
		pointer<int> pint;
		*pint = 1;
then line 7 becomes illegal since operator-> can not return a pointer to an int. Note that main() does not actually use operator->.

This is an annoyance and greatly complicates the writing of such classes in general and those destined for libraries.

The checking of the return-type of operator-> at the point of declaration goes against the "only instantiate what you use" guideline.

So as not to make the treatment of operator-> with templates a special-case, the checking ought to be done at the point of use regardless of whether the given class is parameterized or not. This makes the rule simpler, easier to implement, and easier to teach.

None. Neither the syntactic validity nor the behavior of existing code is affected. All code that currently fails to compile because of an inappropriate return-type with operator-> will still fail; the only difference is when the check is performed and the error given.

Paul J. Lucas

[Personal] [Résumé] [Software] [Contact]
Last updated: April 17, 1998