Today I see this piece of code and I'm wondering to know what it is exactly doing this const reference in an assignment where a new object is created. (I don't know how to name this kind of assignments.)
std::string const& p = s.c_str(); // s is a std::string
I understand that something like std::string const& p = s;
will create a reference p
to s
, but in the line shown we are creating a new object (using the raw pointer from std::string::c_str
).
I've made a MCVE in Coliru with this:
#include <iostream>
#include <string>
void foo(std::string const& s)
{
std::string const& p = s.c_str(); // << here
std::cout << s << " " << p << " " << &s << " " << &p << std::endl;
}
int main()
{
foo("hello");
}
And, as expected the output is showing that a new object was created:
hello hello 0x7ffdd54ef9a0 0x7ffdd54ef950
So, my question is: Is this actually doing something I'm not able to see? Does it have any problem (like a dangling reference) in the code?