c++ - 在 C++ 中返回具有空状态 (NULL) 的对象而不返回指针

标签 c++ c++11

DOM(文档对象模型)规范中,接口(interface)Node有一个方法:

Node GetChild();

它声明如果 Node 没有子节点,则返回值为 NULL。 在 C++ 中实现这种方法而不返回指向子节点的指针的正确方法是什么。 (更好地防止内存泄漏)

建议:

有属性

bool is_null_;

并重载 operator bool() 以返回此值。

Node child = node.GetChild();
if (child) { ... }

最佳答案

稍等一下,图书馆基础知识 TS 将提供 std::experimental::optional .

否则,如果您可以使用 boost::optional , 具有相似的语义。

你可以像这样使用它:

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

关于c++ - 在 C++ 中返回具有空状态 (NULL) 的对象而不返回指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25511984/

相关文章:

C++0x : rvalue reference versus non-const lvalue

c++ - 循环直到没有遇到 std::vector 的任何元素

c++ - 带有 std::vector 的信号和槽:左值问题

c++ - 使用 SDL2 C++ 时出现应用程序无法正确启动 (0xc000007b) 错误

c++ - Pre Z 缓冲区通过 OpenGL?

C++ Boost 1.66 使用 Beast http 请求解析器解析字符串

c++ - 在哪里可以找到 C++11 引用纸质/电子版和书籍引用

c++ - C++ 箭头运算符 (->) 是否在所有情况下都返回左值?

c++ - 宽限期内的 OCILogon - ORA-28002

c++ - 允许编译器优化异常抛出吗?