Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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.

like image 731
Young-hwi Avatar asked Jul 02 '12 06:07

Young-hwi


1 Answers

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).

like image 131
Jerry Coffin Avatar answered Oct 29 '22 17:10

Jerry Coffin