简体   繁体   中英

Conversion from const char * to const std::string &

I think following code should generate an error:

#include <iostream>
#include <string>

static void pr(const std::string &aStr)
{
    std::cout << aStr << "\n";
}

int main(void)
{
    const char *a = "Hellu";

    pr(a);

    return 0;
}

But gcc 4.1.2 compiles it successuflly.

Is it that the constructor of std::string get in the way, creating an instance of std::string?

I believe it shouldn't, because reference is merely an alias to a variable (in this case, there is no variable of type std::string that the reference is referring to).

Is anybody out there to explain why the code compiles successfully?

Thanks in advance.

Yes, given a reference to a constant , the compiler can/will synthesize a temporary (in this case of type std::string ) and bind the reference to that temporary.

If the reference was not to a const object, however, that wouldn't work -- only a reference to const can bind to a temporary object like that (though at least widely used compiler allows a non-const reference to bind to a reference as well).

What you encounter is implicit conversion.

Here is a quote from the C++ Standard (SC22-N-4411.pdf)

1 Type conversions of class objects can be specified by constructors and by conversion functions. These conversions are called user-defined conversions and are used for implicit type conversions (Clause 4), for initialization (8.5), and for explicit type conversions (5.4, 5.2.9).

So the compiler just works as intended and calls the std::string constructor you mentioned.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM