我可以在动态分配中使用jsoncpp吗?

时间:2017-03-16 08:32:46

标签: c++ jsoncpp

我面临一些内存损坏的jsoncpp问题。

当我在本地Json :: Value变量中分配一些值时,有时会得到错误的数据并导致崩溃。

所以我试图通过动态分配制作Json :: value变量并更仔细地检查内存损坏。

无论如何,我的问题是,我可以使用jsoncpp进行动态分配吗?你认为它比以前安全了吗?

我很抱歉我缺少英语。

谢谢!

2 个答案:

答案 0 :(得分:1)

当您想要自己管理树中值的引用时,或者当您想要引用值的内部时,JsonCpp可能会变得不方便。 请参阅以下代码,其中介绍了三种方法,以及两个显示常见陷阱的示例。希望它有所帮助。

请注意,在处理"动态分配"时,通常智能指针非常方便,并且可以降低由于在正确的点分配/删除对象的错误导致的内存泄漏或内存损坏的风险。例如,授予shared_ptr

Json::Value createJsonValue() {

    Json::Value json("a string value");
    return json;  // OK - enforces a copy
}

Json::Value *createJsonValueReference() {
    Json::Value *json_dynamic = new Json::Value("a string value");
    return json_dynamic;  // OK - does not enforce a copy but keeps json value in heap
}

std::shared_ptr<Json::Value> createJsonValueSmartPointer() {
    std::shared_ptr<Json::Value> result(new Json::Value("a string value"));
    return result;  // OK - creates a json::value on the heap and wraps it by a shared_ptr object
}

Json::Value &referenceToLocalJson() {
    Json::Value json("a string value");
    return json;  // Not OK: Reference to stack memory associated with local variable `json` returned
}

const char* getJsonValueContent() {

    Json::Value json("a string value");
    return json.asCString();  // critical: reference to internals of object that will be deleted.
}

int main()
{
    Json::Value copied = createJsonValue(); // will be a copy; lifetime is until end of main
    Json::Value *ptr = createJsonValueReference();  // will be a reference to an object on the heap; lifetime until you call `delete ref`
    std::shared_ptr<Json::Value> smartptr = createJsonValueSmartPointer(); // share_ptr object, managing a reference to an object on the heap; lifetime of shared_ptr until end of main; lifetime of referenced object until the last shared_ptr pointing to it is destroyed

    Json::Value &critical = referenceToLocalJson(); // Critical; will refer to an object that has already been deleted at the end of "referenceToLocalJson"
    const char* content = getJsonValueContent();  // critical: reference to internals of object that will be deleted.

    cout << "copied:" << copied << std::endl;
    cout << "reference:" << *ptr << std::endl;
    cout << "smartptr:" << *smartptr << std::endl;

    // cout << "critical:" << critical << std::endl;  // undefined outcome
    // cout << "content:" << content << std::endl;  // undefined outcome

    delete ptr;  // OK - will free object referred to by ptr

    // smartptr will be deleted together with the json value it refers to at the end of this function; no "explicit" delete
    return 0;
}

答案 1 :(得分:0)

我有一个关于JsonCpp的非常类似的问题,这对于阅读这篇文章的所有人来说都很有趣。

JsonCpp heap object handling memory management