简体   繁体   中英

What type are “C-style strings” and what's its relationship with std::string

I was faced with this question for a C++ exam and as much as I think I know the answer, the question confused me enough that I rather have a "Second opinion" per say... haha.

a) The literal "Hello, World!" is a C-Style string. What is its type?

b) Given that the type of C-style string and the type std::string are different, how is it possible that the line std::string hello("Hello,World!"); compiles without errors/warnings (assuming the <string> header has been included)?

From my understanding the C-Style string is of type (a) array of chars while std::string is of type string... and (b) the reason it compiles is that in C++ the whole casting to chars and all that is done "under the hood" by the type string rather than "in the code".

Am I correct?

Thanks!

What you say is probably close enough to be called "true", although you're missing some detail. The type of the literal "Hello, World!" in C++ is const char[14] . As you say that's an array of chars, but the size is part of the type.

std::string has a constructor that takes const char* , and there's an implicit conversion from const char[14] to const char* . Those two together handle (b).

There's no "casting to chars" involved, though.

In C++, the type of "Hello, World!" is an array of 14 const char and in C the type is an array of 14 char . The trailing null character of the string is a part of the array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM