从函数返回后的std :: string c_str()作用域 [英] std::string c_str() scope after returning from function

查看:833
本文介绍了从函数返回后的std :: string c_str()作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆