将const_cast应用于字符串文字? [英] Apply const_cast to a string literal?

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

问题描述



我可以使用 const_cast< char *>

我需要一些预定义的常量c风格的字符串文字在我的c ++代码。 code>直接在字符串文字?



IE,这是合法的(并且它是一个好主意)对于期望只读的例程 char * 参数?

  const_cast< char *>(PIOFLAG)

或者我应该使用 char * pf =PIOFLAG并使用 pf 作为参数?

解决方案

string在一个使用 char * 但实际上不是修改字符串本身的API中使用,则 const_cast< char *>(SOME STRING)将会罚款。理想情况下,您可以修改API以具有 const 参数,这将使其更容易使用,并反映现实。


I need some predefined constant c-style string literals in my c++ code.

Can I use const_cast<char *> directly on a string literal?

I.E., is this legal (and is it a good idea) for a routine expecting a read-only char* argument?

const_cast<char*>("PIOFLAG")

Or should I just use char *pf="PIOFLAG" and use pf as an argument?

解决方案

If the string is used in an API that takes char * but in fact isn't modifying the string itself, then const_cast<char *>("SOME STRING") will be fine. Ideally, you'd modify the API to have a const parameter instead, which would make it much easier to use, and reflect reality.

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

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