将const_cast应用于字符串文字? [英] Apply const_cast to a string literal?
问题描述
我可以使用 const_cast< char *>
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屋!