关于c ++:从函数返回值时使用c_str()的区别

Differences in use of c_str() when returning a value from a function

如果我有以下两个功能

1
2
3
4
5
6
std::string foo1()
{
    std::string temp;
    ...
    return temp;
}

1
2
3
4
5
6
const char* foo2()
{
    std::string temp;
    ...
    return temp.c_str();
}

和一个以const char *作为输入的函数;

1
void bar(const char* input) { ... }

哪个更安全:

1
bar(foo1().c_str());

要么

1
bar(foo2());

如果我要做的只是将字符串作为输入传递给bar,然后不关心foo函数的返回值,这实际上有关系吗?


1
2
3
4
5
6
const char* foo2()
{
    std::string temp;
    ...
    return temp.c_str();
}

foo2()是不安全的,您正在将const char*返回到局部变量,该局部变量在函数返回时将指向垃圾。

只需使用foo1,这是C ++中一种安全且惯用的方式来返回对象。 NRVO可能会加入
foo1返回时,它将删除temp的副本。

1
2
3
4
5
6
std::string foo1()
{
    std::string temp;
    ...
    return temp;
}

1
2
3
4
5
6
const char* foo2()
{
    std::string temp;
    ...
    return temp.c_str();
}

根本不安全,因为temp将被销毁,因此您将返回一个悬空的指针。


只要未破坏原始字符串对象,c_str的字符数组就有效。这已经被问过了。在函数的最后,temp被破坏了,这意味着foo2()返回了无效的指针。


bar(foo2());简直是错误的……因为当foo2返回时,temp std :: string被破坏,并且c_str()返回的指针现在指向无效的位置。


foo2版本是不安全的,因为从foo2返回时,std::string temp被破坏了,因此c_str()返回的指针无效。 foo1更安全,因为它返回std::string temp的副本。


foo2返回一个指向局部变量内部的指针,该局部变量在退出该函数时会被破坏。 (那很糟)