从函数返回的字符串字面值地址安全可移植? [英] Is returning a string literal address from a function safe and portable?

查看:137
本文介绍了从函数返回的字符串字面值地址安全可移植?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个函数来返回一个只读访问的字符串。



我可以返回类似 std :: string

code>:

  std :: string myFunction()
{
returnstring ;
}

或返回 const char *

  const char * myFunction()
{
returnstring
}

在这种情况下,第二个替代物是否安全和可移植?

$在这种情况下,第二个选择是否安全和可移植?


是!字符串文字的存储分配是 static ,它们在应用程序的生命周期内保持不变。


I need a function to return a string that will only be accessed read-only. The string contents is known at compile time so that I will use a string literal anyway.

I can return something like std::string:

std::string myFunction()
{
   return "string";
}

or return const char*:

const char* myFunction()
{
   return "string";
}

Is the second alternative safe and portable in this scenario?

解决方案

Is the second alternative safe and portable in this scenario?

Yes! The storage allocation of string literals is static and they persist for the lifetime of the application.

这篇关于从函数返回的字符串字面值地址安全可移植?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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