What is the difference between the following ways of printing a string?
std::cout << "hello";
// and
std::cout << std::string("hello");
They both appear to do the same thing.
CodePudding user response:
std::cout << "hello";
uses the operator<<
overload dealing with null terminated character arrays. "hello"
, which is a const char[6]
, decay s into a const char*
when passed as an argument to the operator<<
overload:
template< class CharT, class Traits >
basic_ostream<CharT,Traits>& operator<<( basic_ostream<CharT,Traits>& os,
const char* s );
std::cout << std::string("hello");
uses the operator<<
overload for dealing with strings. std::string
is a typedef
for std::basic_string<char, std::char_traits<char>, std::allocator<char>>
.
template <class CharT, class Traits, class Allocator>
std::basic_ostream<CharT, Traits>&
operator<<(std::basic_ostream<CharT, Traits>& os,
const std::basic_string<CharT, Traits, Allocator>& str);
CodePudding user response:
Case 1
Here we consider the statement:
std::cout << "hello";
In the above statement "hello"
is a string literal of type const char[6]
which decays to a const char*
due to type decay. This const char*
is then passed to the non-member overload of operator<<
given below:
template< class CharT, class Traits >
basic_ostream<CharT,Traits>& operator<<( basic_ostream<CharT,Traits>& os,
const char* s );
Case 2
Here we consider the statement:
std::cout << std::string("hello");
In the above statement the expression std::string("hello")
creates a temporary std::string
object. Now since the std::string
has overloaded operator<<
(given below), that overloaded version of operator<<
will be called and its body will be executed.
template <class CharT, class Traits, class Allocator>
std::basic_ostream<CharT, Traits>&
operator<<(std::basic_ostream<CharT, Traits>& os,
const std::basic_string<CharT, Traits, Allocator>& str);