C++ string literals and static_cast behavior

Post No: 048 A small but interesting thing I recently got to know in C++ is how static_cast behaves with string literals. When I write “hello”, I thought it is a std::string, but it is not. A string literal in C++ is actually of type const char[]. In most expressions, this array decays into a pointer, which is why: auto text = “hello”; makes text a const char*, not a std::string. This is also why static_cast may seem to “cast it to a pointer”. What is really happening is array-to-pointer conversion. The important thing to understand is that std::string and std::string_view are class types. To create them, we need object construction. For std::string: std::string str = static_cast<std::string>(“hello”); For std::string_view: std::string_view sv = static_cast<std::string_view>(“hello”); We can also directly construct them in a cleaner way: std::string str(“hello”); std::string_view sv(“hello”); I got to learn this in a hard way, hope this makes things more easy for someone else. #cpp #cplusplus #programming #softwaredevelopment #coding #learning

To view or add a comment, sign in

Explore content categories