C++ 从函数返回值时c_str()用法的差异
如果我有以下两个功能C++ 从函数返回值时c_str()用法的差异,c++,string,C++,String,如果我有以下两个功能 std::string foo1() { std::string temp; ... return temp; } std::string foo1() { std::string temp; ... return temp; } 及 以及以常量char*作为输入的函数 void bar(const char* input) { ... } 以下哪一项更安全: bar(foo1().c_str()); 或 如果我只想把
std::string foo1()
{
std::string temp;
...
return temp;
}
std::string foo1()
{
std::string temp;
...
return temp;
}
及
以及以常量char*作为输入的函数
void bar(const char* input) { ... }
以下哪一项更安全:
bar(foo1().c_str());
或
如果我只想把一个字符串作为输入传递给bar,而不关心foo
函数的返回值,那么这真的很重要吗
const char* foo2()
{
std::string temp;
...
return temp.c_str();
}
foo2()
只使用 Foo1这是C++中返回对象的一种安全和惯用的方法。可能会起作用
当foo1
返回时,它将删除temp的副本
根本不安全,因为temp
将被销毁,因此您将返回一个悬空指针。foo2
返回一个指向局部变量内部的指针,该变量在退出函数时被销毁。(那太糟糕了)bar(foo2());这是完全错误的。。。因为当foo2返回时,temp std::string将被销毁,c_str()返回的指针现在指向无效位置。只要原始字符串对象未被销毁,c_str的字符数组就有效。在函数结束时,temp
被销毁,这意味着foo2()
返回一个无效指针。foo2
版本是不安全的,因为c_str()
返回的指针无效,因为std::string
temp
在从foo2
返回时被销毁<代码> > Foo1返回一个“代码> STD::String 代码> TEMP < /P>的副本是安全的。谢谢您的所有答案,我不会在C中这样做(我会返回一个MalCube指针),但是我不确定在把STD::string转换成conchar的时候,C++在幕后做什么。如果它有帮助,在C++中,代码> STD::String 等效于MulLoCube指针。它只是碰巧自动释放和strcpy等等。C++需要一种与C.That的思维方式完全不同的思维方式,并欺骗自己,这也是返回Cx()的情况:
const char* foo2()
{
std::string temp;
...
return temp.c_str();
}
std::string foo1()
{
std::string temp;
...
return temp;
}
const char* foo2()
{
std::string temp;
...
return temp.c_str();
}