【发布时间】:2014-06-21 14:00:30
【问题描述】:
首先,一切都发生在 do{}while 循环中的 if{} 语句中。我有一个包含一些 const char 指针的结构。我试图在每次迭代时将信息放入一个带有新字符串值的临时结构中,然后将此结构推入所述结构的向量中,以便当函数退出时,该向量将填充不同的结构对象。
do{
if()
{
sound_device_t newDevice; //<--- Why is this the same mem address each iteration?
//I thought it would be destroyed when it's scope was (the if block)
const char * newPath;
someFunction(&newPath); //puts a string into newPath
newDevice.firstString = newPath; //<-- This works.
QString otherPath(const char *);
//...some QString manipulation...//
newDevice.secondString = otherPath.toLocal8Bit().data(); //<--this doesn't
vector_of_structs -> push_back(newDevice);
}
}while (...)
我的印象是 push_back 将参数结构的值复制到自己的版本中。为什么 QString 会给我带来问题?我使用 QString 是因为它有一些很好的字符串操作函数(即插入和部分),但如果我需要一些有用的东西,我会交换它。
我也尝试过将 QString 的数据放入 char * 中,然后将其 strcpy'ing 到结构中,但结果相同。每次迭代都会重写 newDevice.secondString。
【问题讨论】:
-
只是出于好奇:有什么理由不使用 append 而不是 push_back?另外,为什么不使用 QStringList?
QString otherPath(const char *);无效,顺便说一句。另外,你能总结一下“不起作用”是什么意思吗? newDevice.secondString 是 char* 吗? -
存储
const char*以备后用...为什么不使用std::string或者在这种情况下使用QString?someFunction(const char**)是否在堆上分配? -
感谢您回复@LaszloPapp。我在 std::vector 类中看不到 append 。我在看this page. 我从来没有听说过QStringList。 :) 不过,大多数情况下,我试图避免使用太多 Qt 库,因为我试图让我的程序尽可能小。
-
嘿@Zaiborg。我开始使用 const char * 因为我正在与 DBUS 交互并且所有函数都使用 const char *。在这种情况下,我尝试使用 std::string ,但它也不起作用。我不知道 someFunction() 是否在堆上分配。我该如何检查? (这是一个 DBUS 功能。)
-
请不要编辑问题以表明它已解决,或者您已为其添加了新答案。
标签: c++ qt pointers vector struct