Comparing std::string and C-style string literals
Asked Answered
P

1

9

Suppose I have the following code:

#include <iostream>
#include <string>
#include <iomanip>
using namespace std; // or std::

int main()
{
    string s1{ "Apple" };
    cout << boolalpha;
    cout << (s1 == "Apple") << endl; //true
}

My question is: How does the system check between these two? s1 is an object while "Apple" is a C-style string literal.

As far as I know, different data types cannot be compared. What am I missing here?

Phenetidine answered 26/12, 2019 at 15:53 Comment(2)
basic_string/operator_cmp ((7) in your case).Handicraft
Fwiw, as long as one type can be converted to another, you can generally compare them. You can initialize a std::string from a c-string.Uninterested
D
16

It is because of the following compare operator defined for std::string

template< class CharT, class Traits, class Alloc >
bool operator==( const basic_string<CharT,Traits,Alloc>& lhs, const CharT* rhs );  // Overload (7)

This allows the comparison between std::string and the const char*. Thus the magic!


Stealing the @Pete Becker 's comment:

"For completeness, if this overload did not exist, the comparison would still work; The compiler would construct a temporary object of type std::string from the C-style string and compare the two std::string objects, using the first overload of operator==

template< class CharT, class Traits, class Alloc >
bool operator==( const basic_string<CharT,Traits,Alloc>& lhs,
                 const basic_string<CharT,Traits,Alloc>& rhs );   // Overload (1)

Which is why this operator(i.e. overload 7) is there: it eliminates the need for that temporary object and the overhead involved in creating and destroying it."

Demerol answered 26/12, 2019 at 15:56 Comment(2)
And, for completeness, if this overload didn't exist, the comparison would still work; the compiler would construct a temporary object of type std::string from the C-style string and compare the two std::string objects. Which is why this operator is there: it eliminates the need for that temporary object and the overhead involved in creating and destroying it.Arvonio
@PeteBecker Of course, I have added it to the answer. Thanks for pointing out!Demerol

© 2022 - 2024 — McMap. All rights reserved.