why no compilation error ?

J

Jarek Blakarz

why no compilation error

The following piece of code compiles fine.
I expected it not to compile.

I thought that fun("sth") creates temporary "string" object that cannot be
assigned to lvalue string reference.
It turns out that I was wrong.
Please help me understanding what is going on here and why it is correct.
thanks.

void fun(const string &s) {}

int main(void)
{
fun("sth");
return 0;
}
 
V

Victor Bazarov

why no compilation error

The following piece of code compiles fine.
I expected it not to compile.

I thought that fun("sth") creates temporary "string" object that cannot be
assigned to lvalue string reference.

A reference to a const object *can* be bound to a temporary object.
It's expressly permitted. See sections 12.2 ([class.temporary]) and
8.5.3 ([dcl.init.ref]).
It turns out that I was wrong.
Please help me understanding what is going on here and why it is correct.
thanks.

void fun(const string &s) {}

int main(void)
{
fun("sth");
return 0;
}

V
 
A

Andrey Tarasevich

I thought that fun("sth") creates temporary "string" object that cannot be
assigned to lvalue string reference.
It turns out that I was wrong.
Please help me understanding what is going on here and why it is correct.

You can reproduce the same behavior with

const std::string &cr = "sth";
std::string &r = "sth";

The first will compile, while the second won't.

As you correctly noted, it implicitly creates a temporary object of type
'std::string'. In C++ it has always been possible to bind 'const'
references to temporary objects, which is why the first initialization
is valid.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,982
Messages
2,570,186
Members
46,744
Latest member
CortneyMcK

Latest Threads

Top