Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/127.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 从函数返回值时c_str()用法的差异_C++_String - Fatal编程技术网

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();
}