为什么std :: string不提供转换为const char *? [英] Why does std::string not provide a conversion to const char*?
问题描述
这更像是一个政策或历史问题。为什么决定不会为std :: string提供const char *转换?有恐惧有人可能做printf(%s,s),并相信它会自动转换?对这个问题是否有任何公开讨论?
This is more of a policy or a historical question. Why was it decided not to provide a const char * conversion for std::string? Were there a fear someone might do printf("%s", s) and believe it would automatically convert? Are there any open discussions on this issue?
推荐答案
自动投射几乎总是邪恶的。如果有一个转换 const char *
,一个 std :: string
也可以自动转换为其他指针类型并可能导致很难找到错误。有 c_str()
方法返回 const char *
,所以你仍然可以实现你需要的。此外,类型转换在逻辑上是不正确的 - std :: string
不等同于 const char *
。
Automatic casts are almost always evil. If there were a cast to const char *
, a std::string
could be also automatically cast to other pointer types and that could lead to hard to find bugs. There is the c_str()
method that returns const char *
so you can still achieve what you need. Also, the typecast is not logically correct - std::string
is not equivalent to const char *
.
这篇关于为什么std :: string不提供转换为const char *?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!