Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
262 views
in Technique[技术] by (71.8m points)

c++ - Why does std::string not provide a conversion to const char*?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 *.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...