How to make it clear when an object does not exist in C++?
I have a class which depending on the state of the application and user options may not always be able to exist in any meaningful state.
What is the best way to make it clear when the object does not exist?
Two ideas I've thought of so far and why I don't believe they are not the answer:
- A smart pointer set to NULL when the object doesn't exist, this sends a clear message that there is no object here, however I've read that dynamic memory allocation using 'new' should be the exception not the rule in C++ and it also prevents me being able to pass in by reference to other functions (since the 开发者_StackOverflowpointer may not always point to an object).
- A boolean flag in the object which, when set, causes any methods called to throw an exception. This would require checks in every method and feels like a kludge. I also believe the best practice is that all objects that exist should be valid and we shouldn't need to call a validate (or similar) function because the existence of the object implies it's already valid and ready to have its methods called.
boost::optional<T>
. It exists for exactly this reason.
I think you want the NULL Object pattern.
You inherit from your base class, a "null" implementation of it. So it has the same methods and properties as the main object but doesn't do anything. Then have an instance of this as a constant. Whenever your variable is not in a usable state assign it to the null object. Nothing bad will happen if it's used, and you can check whether it is equal to your null object instance.
You could create a subclass of the object that represents the NULL version of it. See Null Object Pattern on Wikipedia.
Use a shared library, when you use dlsym() to export the symbol, if it is exported successfully, then the object is exist, otherwise the object isn't exist.
精彩评论