【发布时间】:2014-09-08 13:37:28
【问题描述】:
我有一个如下所示的函数,我正在尝试打印 QT 中的值。
void myfunction(
std::string& Service,
std::string& Type,
std::string& Hostname,
std::string& Address,
UNUM16 Port,
std::map< std::string, std::string >& TxtList )
{
qDebug() << "Hostname capacity is : " << Hostname.capacity();
qDebug() << "Hostname is : " << QString::fromStdString(Hostname);
qDebug() << "Port is : " << ntohs(Port);
std::map< std::string, std::string >::iterator iter;
iter = TxtList.find("FwVersion");
}
现在,当我运行该函数时,第一个调试语句会打印字符串容量的正确值。但是第二个调试语句不起作用,它只打印空字符串。而且当我在地图上进行查找时,应用程序就会崩溃。
我也尝试过 QString::fromUtf8(Hostname.c_str()) 函数,即使这样也没有用
有没有办法转换值并在 QT 中打印?
【问题讨论】:
-
通常不应将
std::string作为参考传递。它有自己的复制构造函数。 -
@Qix,通过 const 引用传递它很常见。通过非常量引用应该遵守与通过非常量引用传递其他任何东西相同的规则:如果您需要更改它并传播这些更改。
-
@devana,请发布一个MCVE,其中包含提供您描述的行为的字符串。
-
@chris 他们并没有通过 const 引用传递。
-
@chris 上面的函数是我正在使用的库中的回调函数。我必须使用 std::string 引用本身作为输入参数,并且我不能更改函数的签名。我已经尝试通过创建一个变量作为值类型并在这种情况下使用 QString::fromstdstring 来不使用引用。但不是当字符串被声明为引用时。