从函数返回后的std :: string c_str()作用域 [英] std::string c_str() scope after returning from function
问题描述
我在C ++/MFC中具有以下功能:
I have below mentioned function in 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'中?
1.) What would be the lifetime of abc.c_str() pointer returned by StringFunc(), would it be safely copied to variable 'Temp' after StringFunc() returns ?
2.)CString Temp = StringFunc()是浅复制操作还是深度复制?
2.) CString Temp = StringFunc() is a Shallow copy operation or Deep Copying ?
推荐答案
StringFunc()返回的abc.c_str()指针的生命周期是多少,在StringFunc()返回之后可以安全地将其复制到变量'Temp'吗?
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() function
返回.是的,将副本返回到CString是安全的.
abc
will be valid until StringFunc() function
returns. Yes, it's safe to return a copy to CString.
如果返回指向std::string::c_str()
的指针,则很危险,例如:
If you return a pointer to std::string::c_str()
then it's dangerous, for example:
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()是浅复制操作还是深度复制?
CString Temp = StringFunc() is a Shallow copy operation or Deep Copying ?
它是深拷贝.它从const char*
这篇关于从函数返回后的std :: string c_str()作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!