【发布时间】:2018-11-17 07:55:18
【问题描述】:
我没有遇到以下代码的任何问题,但是将char [] 传递给接受std::string& 作为参数的函数是一种好习惯
const char* function(std::string& MyString)
{
MyString = "Hello World";
return MyString.c_str();
}
int main()
{
char MyString[50];
/*
*Is it good practice to cast like this?
*what possible issues i could face because of this casting?
*/
function((std::string)MyString);
std::cin.get();
return 0;
}
【问题讨论】:
-
这取决于函数的细节。在这种情况下,如果您尝试将
function的返回值保存到您调用它的行之后,它实际上将不起作用,因为返回值仅与您调用它的字符串一样长。但这是一个稍微不同的问题。仅从创建临时对象的角度考虑生命周期管理会遗漏一些东西。一般来说,它可能涉及不必要的副本来构造std::string;如果需要,您可以这样做,但最好编写函数以使用std::string_view代替。
标签: c++ arrays string pointers