我正在处理一些遗留代码,我必须在 cpp 文件中进行一些更改。cpp 文件包含外部“c”块中的整个代码 -
我更新了一个返回 char* 的函数。代码看起来像下面的 func1() 。由于我使用 std::strring 和 stringstream 我在 extern 块之前包含了 sstream 和 string 头文件。下面的函数是从 c 和 cpp 文件中调用的。所以我不能在这里返回 std::string -
char* func1(someStruct* pt){
std::strig nam = somefunc(pt);
//have to append some integer in particular format
std::stringstream ss;
ss<<nam<<pt->int1 ......;
nam = ss.str();
//More code here for returning char* based on queries - (a)
}
在调用此函数的地方之一 -
void otherFunc(.....){
//......
char* x = func(myptr);
if(based_on_some_condition){
char* temp = func3(x); //returns a char* to dynamically allocated array.
strcpy(x,temp); //copying (b)
}
//..........
}
以下是我的查询 -
1) 在 (a) 我可以以以下 2 种形式返回 char*。我必须做出决定,以便在 (b) 处复制不会导致任何未定义的行为 -
i)Create a char array dynamically with size = nam.length()+10 (extra 10 for some work happening in func3).<br>
char* rtvalue = (char*)calloc(sizeof(char),nam.length()+10);
strcpy(rtvalue,nam.c_str());
return rtvalue;
And free(temp); in otherFunc() after strcpy(x,temp);
ii) Declare 'nam' as static std::string nam;
and simply return const_cast<char*>(nam.c_str());
Will defining 'nam' with static scope ensure that a correct return happen from function (ie no dangling pointer at 'x')?
More importantly, can I do this without worrying about modification happening at (b).
哪一个是更好的解决方案?