且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么std :: string不提供转换为const char *?

更新时间:2022-12-14 08:03:41

自动投射几乎总是邪恶的。如果有一个转换 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 *.