对于非静态字符串,字符串到字符* 转换失败

String to char* conversion fails for non static string

本文关键字:字符串 转换 失败 字符 于非 静态      更新时间:2023-10-16

注意: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"));
    }
}
即使

secondCopystatic的(就像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);

aPayloadpayloadString变成,payloadString成为从&currString[0];(建议使用c_str()成员函数,这没有解决你在这里有问题(所以当functionName超出范围时,currString变量会自动调用他的析构函数和 char* payloadString = &currString[0];成为无效指针。