对于非静态字符串,字符串到字符* 转换失败
String to char* conversion fails for non static string
注意:API 使用 char* 而不是 const char *,所以我不能使用 c_str(( 函数调用 sendCall 是一个 Aysnchronous 调用
下面是我的代码,当我使用时它可以正常工作
char* payloadString = >&currString[0];
但是当我尝试使用
char* payloadString = &secondCopy[0];
它失败了,我无法理解原因。我想在下面的代码中创建一个动态可更新的字符串,例如 desiredString,它采用版本变量并将其分配给静态字符串 secondCopy 并能够使用它而不是 currString,但我想我通过使用修改后的静态字符串在运算符地址上犯了一些错误。请提出解决方法。
void functionName()
{
std::string version;
version = "ABC";
static std::string currString= "<Version="3.0" Ret="false"/>";
std::string desiredstring= "<Version="+version+" Ret="false"/>";
static std::string secondCopy = desiredstring;
char* payloadString = &currString[0];
//char* payloadString = &secondCopy[0];
XDSC::Definition aDefinition("sname", "sid");
try
{
std::auto_ptr<otf::ClientSession> aSession;
aSession = getResources()->getManager().getSession("XML");
aSession->setAttachedToServerConversation(true);
aSession->setLogicalName("xyz");
aSession->setITOReturnPackage("svrc");
boost::shared_ptr<Payload> aPayload = boost::make_shared<Payload>(aDefinition, "3.0",payloadString, strlen(payloadString));
sendCall(aSession.get(), aPayload,"SRING", true);
}
catch(std::exception& e)
{
throw (exception(ERROR,"SendCall Failed to Send"));
}
}
即使
secondCopy
是static
的(就像curString
一样(,每次调用functionName
时,您都会给它分配一个局部变量。这意味着指向 string
对象内部char*
的基础指针可能会在对函数的两次调用之间更改。如果 sendCall
函数是异步的,或者将指针保存在某个位置供以后使用,则在再次调用该函数时,可能会发现它无效。
例:
char* foo(string s)
{
static string ss = "aaa";
ss = s; //assignment operator, the char* inside the string class may be reallocated
char* pointer = &ss[0];
return pointer;
}
void main()
{
string s1 = "a";
char* p1 = foo(s1); //p1 is OK for now
string s2 = "b";
char p2* = foo(s2); //p1 is probably NOT OK
return 0;
}
如果你在 paralell 中运行 sendCall
函数:
sendCall(aSession.get(), aPayload,"SRING", true);
aPayload
从payloadString
变成,payloadString
成为从&currString[0];
(建议使用c_str()
成员函数,这没有解决你在这里有问题(所以当functionName
超出范围时,currString
变量会自动调用他的析构函数和 char* payloadString = &currString[0];
成为无效指针。
相关文章:
- 如何将包含epoch时间的十六进制字符串转换为time_t
- 当字符串存储在变量中时,如何将字符串转换为wchar_t
- 如何将这个std::字符串转换为std::基本字符串
- 如何正确将字符串转换为标准::时间::system_clock::time_point?
- 如何在C++中将十六进制字符串转换为文本数据
- 需要帮助在 c++ 中将字符串转换为字符 ----错误 "const char *" 类型的值不能用于初始化 "char" 类型的实体
- 如何从字符串转换为双精度*
- C++:如何将 unix 时间的字符串转换为 *tm?(使用时间错误:"cannot convert 'String' to 'tm*' ")
- 如何在C++中将 Python 字符串转换为其转义版本?
- 如何在 C++11 中将标准::字符串转换为标准::u32字符串?
- 如何将整数字符串转换为整数的二维向量?
- 使用 "stringstream " 将字符串转换为整数
- 将字符串转换为浮点数或整数,而无需使用内置函数(如 atoi 或 atof)
- 将文件复制到自定义位置,存在字符串转换问题
- 将ANSI C字符串转换为UNICODE
- 如何将节点 V8 字符串转换为 C++ 字符串
- 在C++中将字符串转换为双精度,而无需科学记数法
- 使用从文件(stod、strtod、atof)中提取的数据C++从字符串转换为双精度.csv
- 如何在C++中将字符串转换为双精度?
- 将字符串转换为无符号字符数组/字节数组