gpt4 book ai didi

c++ - 从函数返回后的 std::string c_str() 作用域

转载 作者:行者123 更新时间:2023-11-30 00:52:23 26 4
gpt4 key购买 nike

我在 C++/MFC 中有下面提到的函数:

CString StringFunc()
{
std::string abc = "Hello";

return abc.c_str();

}

int main()
{
CString Temp = StringFunc();

Use_Temp(Temp);
}

1.) StringFunc() 返回的 abc.c_str() 指针的生命周期是多长,它会在 StringFunc() 返回后安全地复制到变量“Temp”吗?

2.) CString Temp = StringFunc() 是浅拷贝还是深拷贝?

最佳答案

What would be the lifetime of abc.c_str() pointer returned by StringFunc(), would it be safely copied to variable 'Temp' after StringFunc() returns ?

abc 将一直有效,直到 StringFunc() 函数 返回。是的,将拷贝返回到 CString 是安全的。

如果你返回一个指向 std::string::c_str() 的指针那么它是危险的,例如:

const char* EvilFunc()  // bad, dont' do it
{
std::string abc = "Hello";
return abc.c_str();
}

const char* p = EvilFunc(); // p becomes wild pointer when EvilFunc returns

CString Temp = StringFunc() is a Shallow copy operation or Deep Copying ?

这是深拷贝。它从 const char*

构造一个新的 CString 对象

关于c++ - 从函数返回后的 std::string c_str() 作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19244331/

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