2012-07-05 1088 views
1

我使用Json-cpp解析我的配置文件,我得到som奇怪的行爲與asCString() ..任何人都可以解釋爲什麼輸出爲2是空的?Json cpp asCstring()返回空cstring當存儲在變量中

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

回答

2

我懷疑root["redis"].get("host", "localhost")root["redis"]返回Value,而不是一個Value參考。那Value對象會一直存在直到表達式結束,在2的情況下臨時對象Value將被銷燬,留下cstr作爲懸掛指針。取消引用懸掛指針時的行爲未定義。

1的情況下,str是由asString()返回的std::string的副本。

3的情況下,臨時Value將存活直到允許由asCString()返回的const char*被成功處理表達式(;)的端部。

來解決,或者:

  • 變化cstrstd::string類型,它會複製返回const char*,或
  • 製作的由get()返回Value的副本,並查詢它,而不是root[]

編輯:

在此基礎上sourceValue.get()回報Value所有變體。所以原因如上所述。

+0

是的,get()確實會返回一個值。謝謝! – Jesper 2012-07-05 12:38:49