I'm searching for a substring using string::find
in C++. When I defined a string using const auto
and used the variable later down, eclipse replaced .
with ->
.
I found this SO thread which concludes that auto foo = "bar"
is deduced to a (const char *) foo = "bar"
. So eclipse is correct converting .
to ->
even though I was a bit baffled to begin with. I assumed incorrectly auto
would become std::string
.
Would there be a downside deducing auto foo = "bar"
to std::string
instead of const char *
? Increased code size, slower performance?
Your code could have a million classes that can be constructed implicitly from a const char *
. Why should std::string
be chosen?
auto
simply saves some keyboard typing you if you want a variable with the same type of the expression¹ , not if you want to create a different object.
(1) more or less; things as always get somewhat hairy with C++...
Well, likely, you have just answered your own question. std::string takes slightly more space (it has size counter), its creation involves dynamic allocation etc.
The lack of a complex string type may seem an anachronism nowadays, but since C++ is oriented toward a complete replacement of C with its low-level efficiency, it's pretty explainable.
Moreover, std::string
is just a library class. you can choose a different string type, eg QString or std::experimental::string_view , if your task requires it. BTW, string_view
is much more similar to const char[]
since it doesn't provide dynamic manipulations at all and can be used in constexpr
"Foobar" is a string literal and not a std::string
. This is stored as const char[7]
in a read only section of your binary.
std::string
te type has an implicit conversion from const char *
because it has a single argument constructor without it being explicit which is invoked if you write: std::string s = "foobar";
. Note that the default argument of allocator is assigned on the constructor.
Using const auto
gives you the actual type instead of a converted type. So converting a string literal to std::string
actually creates another object that references the literal.
http://en.cppreference.com/w/cpp/language/string_literal http://en.cppreference.com/w/cpp/string/basic_string
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.