<po************ **@yahoo.comsch rieb im Newsbeitrag
news:11******** **************@ 75g2000cwc.goog legroups.com...
Just looking for opinion on which of the 3 methods below people use in
their code when they convert a 'const char *' to a 'const std::string
&'
came across #3 in someone's code and I had to think for a sec. At
first I read it as converting a 'const char *' to a 'std::string *'
void f(const std::string &s)
{
std::cout << s.size() << "\n";
}
int main()
{
const char *c="sal";
f(c); //1
f(std::string(c )); //2
f(static_cast<s td::string>(c)) ; //3
return 0;
}
If it works without a cast, you shouldn't use a cast. So (1) is probably the
best solution, not only because it's also the one with least typing. This
will also help you not to cast away errors, which may happen if you have to
change the type of the function's argument or the value passed to it latter.
In your example, that might be not likely to happen, but with other types,
like int's and long's it could cause problems.
Except for their syntax (2) and (3) do basically the same, so if you really
have to use a cast, use whichever looks better to you. There is less typing
with a function-style cast (2), but it is easier to find a static_cast in a
large program, especially with tools like grab. Also, a static_cast (or
other *_cast's) can be used for all types whereas function-style casts can
only be used for named types. For example, you can use static_cast<uns igned
int>(...) but you cannot use unsigned int(...) as a cast.
Regards
Heinz