用Cstring替换LPCTSTR安全吗?
功能的参数需要lpctstr
type actible;如果我们传递cstring
类型变量怎么办?在这种情况下,它是安全的还是我们应该考虑的东西?
例如,此功能:
Add(new CAToolbar, _T("Command Toolbar"), xtpBarTop);
在这里,我想用lpctstr
type _T(“命令工具栏”)用cstring str;
替换。这样的事情:
Add(new CAToolbar, str , xtpBarTop);
安全吗?
A parameter of function requires an LPCTSTR
type variable; what if we pass a CString
type variable? Is it safe or is there anything that we should look at in this case?
For example this function :
Add(new CAToolbar, _T("Command Toolbar"), xtpBarTop);
Here I want to replace _T("Command Toolbar")
(LPCTSTR
type) with CString str;
. Something like this:
Add(new CAToolbar, str , xtpBarTop);
Is it safe ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在这种情况下,
cstring
类具有运算符lpctstr()
,该将字符串的内容返回为c风格,nul-enul-terminatedchar> char
或<代码> wchar_t 数组(嗯,是其第一个元素的指针),具体取决于“字符集”选项的当前编译器设置(即是否Unicode
和/或_unicode
是/定义)。因此,返回的类型将(或应该)匹配所需的const char*
vsconst wchar_t*
指针类型用于您的功能参数。 (请注意,这是不是 可用于不是const
合格的功能参数的安全参数)。在“旧时代”中,我使用了一些编译器,这些编译器会在执行此操作时抱怨'隐式'转换,因此我使用了
cstring :: getString()
函数。但是,这些确实 同样的事情。从“ atlsimpstr.h”标题:重要说明:使用此“隐式转换”的一种情况是不是安全的安全是对 variadic griadic参数,例如
printf
或.form> .format()
cstring
本身的成员;在这种情况下,编译器(正确)将(正确)抱怨非便携式使用类对象的使用。采用以下代码:Clang-CL编译器给出此错误:
,甚至MSVC本身也给予:
,您可以使用前面提到的
.getString()
函数,也可以进行转换 explicit :Generally (see note, below), yes, it is safe. The
CString
class has anoperator LPCTSTR()
, which returns the content of the string as a C-style, nul-terminatedchar
orwchar_t
array (well, a pointer to its first element), depending on the current compiler setting of the "Character Set" option (i.e. whether or notUNICODE
and/or_UNICODE
is/are defined). Thus, the returned type will (or should) match the requiredconst char*
vsconst wchar_t*
pointer type for your function parameter. (Note that this is not safe to use for function parameters that are notconst
qualified).In "olden days", there were some compilers that I used that would complain about the 'implicit' conversion when doing just this, so I used the
CString::GetString()
function, instead. However, these do exactly the same thing. From the "atlsimpstr.h" header:Important Note: One case where using this "implicit conversion" is not safe is for functions that take variadic arguments, like
printf
or the.Format()
member ofCString
itself; in such cases, the compiler will (rightly) complain of non-portable use of a class object. Take the following code:The clang-cl compiler gives this error:
And even MSVC itself gives:
In such a case, you can either use the
.GetString()
function mentioned earlier, or make the conversion explicit:cstring
包含lpctstr
的隐式转换操作员。它是为此精确使用而设计的。这是您传递
const
字符串的事实,无法修改使其安全。CString
contains an implicit conversion operator forLPCTSTR
. It was designed for this exact usage.It's the fact that you're passing a
const
string that can't be modified that makes it safe.