1

Json-cpp を使用して構成ファイルを解析していますが、asCString()で奇妙な動作が発生します。

#include <iostream>
#include <fstream>
#define JSON_IS_AMALGAMATION
#include "json/json.h"
using std::cout;
using std::endl;

int main(int argc, char** argv) {
    Json::Value root;
    Json::Reader reader;
    std::ifstream config("dev.json", std::ifstream::binary);
    if (!reader.parse(config, root, false)) {
      cout << "Could not parse json" << endl;
      return 1;
    }
    std::string str = root["redis"].get("host", "localhost").asString();
    const char* cstr = root["redis"].get("host", "localhost").asCString();
    cout << "1:" << str << endl;
    cout << "2:" << cstr << endl;
    cout << "3:" << std::string(root["redis"].get("host", "localhost").asCString()) << endl;
    config.close();
    return 0;
}

出力:

c++ -o test test.cpp jsoncpp.cpp
1:127.0.0.2
2:
3:127.0.0.2

私のjsonデータ:

{ "redis": { "host": "127.0.0.2", "port": 6379 } }
4

1 に答える 1

2

root["redis"].get("host", "localhost")またはへの参照ではなく、 をroot["redis"]返すと思われます。そのオブジェクトは式の最後まで存続し、一時オブジェクトの場合は破棄され、ダングリング ポインターとして残ります。ダングリング ポインターを逆参照するときの動作は未定義です。ValueValueValue2Valuecstr

の場合、1はによって返されstrた のコピーです。std::stringasString()

の場合3、テンポラリは式 ( )Valueの終わりまで存続し、によって返された が正常に処理されます。;const char*asCString()

解決するには、次のいずれかを行います。

  • のタイプをcstrto に変更するstd::stringと、返されたconst char*、または
  • Valueによって返された のコピーを作成し、get()ではなくクエリを実行しますroot[]

編集:

このsourceに基づいて、 のすべてのバリアントは をValue.get()返しますValue。ということで、原因はご指摘の通りです。

于 2012-07-05T10:49:02.110 に答える