从 API 返回字符串文字 [英] Returning a string literal from an API

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

问题描述

我正在编写用户 API,以这种方式返回 const char* 值是否正确?

I'm writing a user API, is it right to return a const char* value this way?

const char * returnErrorString(int errorCode)
{
   switch(errorCode)
    ...
   return "This error code means that...";
}

我不喜欢以这种方式返回字符串文字,但由于 RVO 优化,它们在被用户读取之前不应该被销毁,这是正确的吗?对此有什么建议吗?

I don't like returning string literals this way but they shouldn't be destroyed before being read by the user due to RVO optimizations, is this correct? Any suggestion on that?

推荐答案

没关系.

字符串文字在程序生命周期中具有固定地址.您可以将其地址作为指向任何地方的指针传递.当程序处于活动状态时,字符串文字不会销毁.

String literal has a fixed address during program's life. You can pass its address as pointers to everywhere. String literals will not destroy while the program is alive.

尽量不要修改它们会调用未定义的行为.根据第 2.14.5 节:尝试修改字符串文字的效果未定义."

Just try not to modify them which invokes undefined behavior. Per § 2.14.5 : "The effect of attempting to modify a string literal is undefined."

这篇关于从 API 返回字符串文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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