Re: Checking for null pointer for structure
In article <hlgin9$gcr$1@news.eternal-september.org>, alfps@start.no
says...
As I understand it you want TopStruct to have an optional NestedStruct.
Some TopStruct-s will have a NestedStruct, some will not.
The question is, will any given TopStruct ever /acquire/ or /lose/ a
NestedStruct, or is a TopStruct created with/without a NestedStruct and staying
that way for its lifetime?
If it stays that way for its lifetime, then a natural solution is to use
inheritance.
I wouldn't agree. There are several things I see with this solution
that make me question it.
1 - Although the OP used "NestedStruct" as his name, he didn't actually
nest it. There's nothing here that tells us that there's no use for
"NestedStruct" outside of "TopStruct".
2 - We don't know that even if #1 is as we are assuming (only used
within the context of TopStruct) that it will continue to be so.
3 - TopStruct cannot be used as a value type except when it doesn't have
the "NestedStruct". It must always use pointer semantics.
The first and second problem are not inherent problems, at least not in
this very specific case (could be in other cases), but it does force all
clients of "NestedStruct" to also hold uninteresting information
inherited from "TopStruct".
The third issue may or may not come up, but there's no reason to force
pointer semantics on something that doesn't necessarily need it.
You may buy some pointer safety with this design but there's a better
option that will provide that same safety without the inheritance,
dynamic_cast, and will give the OP what we should always prefer over
inheritance: composition. That better method is boost::optional.
struct NestedStruct { std::string x; };
struct TopStruct
{
std::string ggg;
boost::optional<NestedStruct> nested;
};
while ( top = GetStructs() )
{
if (top->nested)
do_things_with_nested(*top->nested);
}
The boost::optional template will return false for its bool operator
when it hasn't been assigned a value. Of course, if the OP needs to
make sure that TopStruct either has/nothas a nested for its lifetime
they need to make it a private member and only provide an accessor.
The reason we prefer composition over inheritance includes the three
problems I stated above and can be read about in "C++ Coding Policies"
as I recall. If the OP is not allowed to use boost, the optional
template should be easy enough to replicate.
Of course, there could be other governing forces that would lead one to
chose your method instead of mine. I can't know for sure that they
don't apply in this case but, based on the OP's code, I'm tending to
assume they do not.
--
http://crazyeddiecpp.blogspot.com