Summary
My colleague Matthew Wilson made a post recently suggesting that overloading operator&() should be avoided. While I agree with much of what he says, I would like to suggest a valid use for overloading operator&() which enables writing safer code.
Advertisement
In response to Matthew Wilson's recent post at the C++ Source about overloading operator&(), I would like to submit a valid use case. Consider the following code:
SomeObject o;
SomeObject* p;
p = &o;
delete p; // dumb but legal
I know you are thinking that the code example is simply asinine, but it is intended as a purely artificial example of what can and does happen in real world scenarios. This is due to what I percieve as a flaw in the C++ type system, which has only one kind of pointer. If you think about it from, it does seem silly for a strongly typed language to allow you to so easily delete stack allocated objects. This can be easily fixed by writing some trivial pointer classes which I call unsmart pointers.
You can use an undeletable unsmart pointer to represent the return type of a call to operator&(). An unsmart pointer is a pointer class which does not automatically
destroy the resource, and undeletable means that the pointer does not provide any method to delete the resource it references.
Consider the following implementation of SomeObject which overloads operator&().
#include <ootl/ootl_ptr.hpp>
struct SomeObject {
typedef ootl::ptr<SomeObject, !ootl::deletable> undeletable_ptr;
undeletable_ptr operator&() {
return this;
}
};
int main() {
SomeObject o;
SomeObject* p;
p = &o; // compiler error; undeletable pointers can not be assigned to raw pointers.
delete p;
return 0;
}
Today I just sent in my final revision on make next installment of Agile C++ for the C++ Users Journal, Unsmart Pointers Part 1, which not surprisingly covers undeletable and their complement deletable pointers in more depth.