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

I think the 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 will compile it successfully.

Is this what the std :: string constructor interferes with by creating an instance of std :: string?

I believe that this is not so, because the link is just an alias of the variable (in this case there is no variable of type std :: string referenced by the link).

Can anyone explain why the code compiles successfully?

Thanks in advance.

+5
source share
2 answers

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

const, - const , (, , bind ).

+10

, , - .

++ Standard (SC22-N-4411.pdf)

1 . ( 4) (8.5) (5.4, 5.2.9).

, std::string, .

+2
source

All Articles