The following occurred to me while thinking about a way for storing NULLs safely. It's just a quick-shot, so it's heavily debatable, and what I'm aiming at is really something that is supported by the language, or at least by a very short language construct - avoiding the clumsy getter/setter semantics. I just couldn't do it quickly in C++...
#include<iostream>
#include<exception>
using namespace std;
class IntMaybeNull {
private:
int *thePointer;
bool hasBeenAsked;
public:
IntMaybeNull(int *aPointer) : thePointer(aPointer), hasBeenAsked(false) {}
void setPointer(int *newPointer) {
thePointer = newPointer;
hasBeenAsked = false;
}
bool ask() {
hasBeenAsked = true;
return (thePointer != NULL);
}
int *getPointer() const {
if (hasBeenAsked && thePointer != NULL)
return thePointer;
else
throw exception();
}
};
int main() {
int x = 20;
IntMaybeNull i(&x);
try {
int *ii = i.getPointer();
} catch(exception e) {
cout << "dereferencing without asking - buuuh!" << endl;
}
try {
if (i.ask()) {
int *ii = i.getPointer();
cout << *ii << endl;
}
} catch(exception e) {
cout << "dereferencing without asking - buuuh!" << endl;
}
return 0;
}
Keine Kommentare:
Kommentar veröffentlichen