qreon qreon - 3 years ago 178
C++ Question

How does C++ know anything between "quotation marks" is a std::string?

This might be off-topic since there is no code, no output, no anything, but here goes.

The only way I see C++ can know

"this"
is a
std::string
is because the quotation mark is a language construct, much like the
char
between single quotes.

But I would be really surprised if it was the actual answer: does that imply
std::string
is the only way C++ has to interpret text between quotation marks? Then the standard lib would not be just an extension, but a part of C++.

What if I want to develop my own
MyString
class, and I want to create
MyStrings
on the fly using quotation marks: would I be able to do it or is the
""
syntax inevitably linked to the
std::string
?

I also thought about
""
being an operator (after all C++ has
operator()
), but I couldn't find anything about that.

Answer Source

Let's clear up some misconceptions. The type of a string literal is a const char[], not a std::string. For example, the type of "this" would be const char[5] (there is a null-terminator).

does that imply std::string is the only way C++ has to interpret text between quotation marks?

No (it's not std::string) and there are multiple prefixes for utf-8 strings and wide character strings, like L"wide".

then the standard lib would not be just an extension, but a part of C++.

That's true, but not for string literals. You have the type of nullptr which is std::nullptr_t. There is also std::byte that gets special treatment by the standard. A std::initializer_list constructor is chosen when using list initialization. The result of sizeof is a std::size_t and of typeid it is a std::type_info. There may be others I can't think of right now.

would I be able to do it or is the "" syntax inevitably linked to the std::string?

It's not a std::string, but yeah, that's not possible. What you can do however is define a user-defined literal. std::string has one:

using namespace std::string_literals;
auto string = "this"s;

static_assert(std::is_same_v<decltype(string), std::string>); // ok
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download