1

细节:

我使用这个 github 项目将 Json 转换为对象。

https://github.com/ereilin/qt-json

有了这个json:

{
    "bin": "/home/pablo/milaoserver/compile/Devices01.olk",
    "temp":"/home/pablo/milaoserver/temporal/",
    "port": "1234",
    "name": "lekta",

}

用这两行我创建了两个 char 指针:

 char* bin = configuration["bin"].toString().toLatin1().data();
 char* temp = configuration["temp"].toString().toLatin1().data();

调试应用程序我有正确的字符串。

但是,当我使用它们时,具体而言,“bin”字符变为

`hom 

任何想法?

评论中的解决方案:

问题在于数据的“持久性”。

我找到了解决方案:

std::string binAux(configuration["bin"].toString().toLatin1().data());
std::string tempAux(configuration["temp"].toString().toLatin1().data());

char* bin = new char[binAux.size()+1] ;
strcpy(bin, binAux.c_str());

char* temp = new char[tempAux.size()+1] ;
strcpy(temp, tempAux.c_str());
4

4 回答 4

3

您的错误是由于临时对象。

toString()创建一个在分号后不再可用的临时对象。

标准状态:

12.2 临时对象 [class.temporary]

3/ [...]临时对象被销毁作为评估完整表达式 (1.9) 的最后一步,该完整表达式(1.9) (词法上)包含它们被创建的点。即使评估以抛出异常结束也是如此。销毁临时对象的值计算和副作用仅与完整表达式相关联,与任何特定子表达式无关。

也就是说,当你想访问它时,你有Undefined Behavior

这应该可以解决您的问题:

QString str = configuration["bin"].toString().toLatin1();
QByteArray ba = str1.toLatin1();
char *bin = ba.data();

但是你想用char*什么?你在 C++ 中,使用std::stringorQstring代替:

#include <string>

std::string bin(configuration["bin"].toString().toLatin1().data());
于 2013-08-23T11:14:45.350 回答
0

你能试试像

std::string sbin(configuration["bin"].toString().toLatin1().data());
std::string sTemp(configuration["temp"].toString().toLatin1().data());
于 2013-08-23T11:15:00.913 回答
0

toString()创建一个QString立即删除的对象,因此其中包含的数据将被释放。我建议您将数据存储在 a 中,QString直到您使用它char* bin

于 2013-08-23T11:22:50.940 回答
0

您的解决方案可能会更短,如下所示:

char* bin = strdup(configuration["bin"].toString().toLatin1().data().c_str());
char* temp = strdup(configuration["temp"].toString().toLatin1().data().c_str());

strdup()几乎可以完成您所做的所有事情。

于 2013-08-23T11:32:33.023 回答