gpt4 book ai didi

c++ - 从函数返回值时使用 c_str() 的差异

转载 作者:太空狗 更新时间:2023-10-29 23:23:21 26 4
gpt4 key购买 nike

如果我有以下两个函数

std::string foo1()
{
std::string temp;
...
return temp;
}

const char* foo2()
{
std::string temp;
...
return temp.c_str();
}

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

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

哪个更安全:

bar(foo1().c_str());

bar(foo2());

如果我只想将一个字符串作为输入传递给 bar,然后不关心任何一个 foo 函数的返回值,这真的很重要吗?

最佳答案

const char* foo2()
{
std::string temp;
...
return temp.c_str();
}

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

只需使用 foo1,这是 C++ 中返回对象的一种安全且惯用的方式。 NRVO可能会启动这将在 foo1 返回时删除 temp 的拷贝。

std::string foo1()
{
std::string temp;
...
return temp;
}

关于c++ - 从函数返回值时使用 c_str() 的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14748860/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com