kestutisb
kestutisb

Reputation: 261

Return object with empty state (NULL) in C++ without returning a pointer

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) { ... }

Upvotes: 2

Views: 310

Answers (2)

Michael
Michael

Reputation: 968

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;
}

Upvotes: 4

justanothercoder
justanothercoder

Reputation: 1890

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

Upvotes: 2

Related Questions