Here is a sample code:
auto size = "Hello, world"; std::cout << sizeof(size); The console displays 4. I can not understand what type of data does the compiler use to store this string?
Here is a sample code:
auto size = "Hello, world"; std::cout << sizeof(size); The console displays 4. I can not understand what type of data does the compiler use to store this string?
C ++ string literals have types of constant character arrays. This literal "Hello, world" has type const char[13]
Used as an initialization expression, it is implicitly converted to a pointer to its first element, which is of type const char *
Accordingly, the size variable is of type const char * .
You can verify this by running the following code snippet
auto size = "Hello, world"; std::cout << typeid(size).name() << std::endl; If you wrote this
decltype(auto) size = "Hello, world"; std::cout << sizeof(size) << std::endl; then the size variable would be a reference to a string literal and had the type const char ( & )[13] , and the sizeof operator would return the value 13 .
From an abstractly naive point of view, in this case, the acceptable types for the left side of initialization are const char (&)[13] , [const] char[13] and const char * .
The behavior will accordingly depend on how the language rules describe the type deduction for the auto specifier in such a declaration. These rules coincide with the good old classical deduction rules of the types of template arguments for template functions that say that in this case the type of "pointer" should be deduced (and not the type of "array" or type of "link"). Those. in this case should be the same as the example
template <typename T> void foo(T) { std::cout << sizeof(T) << std::endl; } int main() { foo("Hello, world"); // специализируется как `foo<const char *>` } If you wish, both in your case and in the example with the function above, you can direct the deduction in a different direction.
auto &size = "Hello, world"; and get size type const char (&)[13] and sizeof , returning 13.
Note that neither in the first nor in the second case does a copy of the original string literal occur, i.e. no additional "string storage" arises. The "stored string" in these cases is only the original string literal and is stored as it has been stored since the beginning of time: as a static immutable object.
Pointer to char sizeof (char *)
sizeof(const char *) - AnTSource: https://ru.stackoverflow.com/questions/622310/
All Articles