0

親切に悪い方法で、rapidXML を使用して構成ファイルの値を取得しています。

xml_document<> doc;
doc.parse<parse_full>(buffer);
int a = atoi(doc.first_node("master")->first_node("profile")->first_node("width")->value());

ノードが存在しない場合、「first_node」は 0 を返すため、「->value()」がクラッシュします。新しい xml_node を返すとクラッシュは修正されますが、メモリ リークはどうでしょうか?

これは、新旧の return を使用した RapidXML の関数です。

    xml_node<Ch> *first_node(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const
    {
        if (name)
        {
            if (name_size == 0)
                name_size = internal::measure(name);
            for (xml_node<Ch> *child = m_first_node; child; child = child->next_sibling())
                if (internal::compare(child->name(), child->name_size(), name, name_size, case_sensitive))
                    return child;
            return new xml_node<Ch>(node_document);
            //return 0;
        }
        else
            return m_first_node;
    }
4

2 に答える 2

0

次のような例外を使用する必要があります。

int a;
try
{
    xml_document<> doc;
    doc.parse<parse_full>(buffer);
    a = atoi(doc.first_node("master")->first_node("profile")->first_node("width")->value());
}
catch(NodeNotExists &ex)
{
    // process error condition
}

また、rapidxml コードを変更したくない場合は、次のようなラッパー関数を使用します。

template<typename T>
T* notnull(T* arg)
{
    if (arg == 0)
        throw NodeNotExists();
    return arg;
}
于 2012-11-06T15:13:19.740 に答える