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

查看:226
本文介绍了从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天全站免登陆