在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/