2

In DOM (Document Object Model) specification, interface Node has a method:

Node GetChild();

It states that if Node has no child then a return value is NULL. What is the right way to implement this approach in C++ without returning a pointer to a child Node. (Better to prevent from memory leaks)

Suggestion:

Have an attribute

bool is_null_;

and overload operator bool() to return this value.

Node child = node.GetChild();
if (child) { ... }
1
  • 1
    Return a smart pointer instead. Commented Aug 26, 2014 at 17:45

2 Answers 2

4

Waiting a bit now, but the Library Fundamentals TS will be providing std::experimental::optional.

Elsewise if you can use boost::optional, which has similar semantics.

You can use it like:

using std::experimental::optional;

optional<Node> GetChild();

auto child = node.GetChild();
if (child) {
  const Node& childNode = child.value();
} else {
  std::cerr << "parent had no child" << std::endl;
}
Sign up to request clarification or add additional context in comments.

2 Comments

const Node& childNode = *child; is the way the cool kids do it.
const Node& childNode = *child; You have to take make sure not to release child. And passing around this reference in other classes methods might be a problem. I prefer std::shared_pointer<Node>
2

Such thing as boost::optional will help you: http://www.boost.org/doc/libs/1_56_0/libs/optional/doc/html/index.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.