Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   C++ (http://www.velocityreviews.com/forums/f39-c.html)
-   -   why no compilation error ? (http://www.velocityreviews.com/forums/t956571-why-no-compilation-error.html)

Jarek Blakarz 01-16-2013 02:38 PM

why no compilation error ?
 
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;
}

Victor Bazarov 01-16-2013 02:56 PM

Re: why no compilation error ?
 
On 1/16/2013 9:38 AM, Jarek Blakarz wrote:
> 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
--
I do not respond to top-posted replies, please don't ask

Andrey Tarasevich 01-16-2013 06:36 PM

Re: why no compilation error ?
 
On 1/16/2013 6:38 AM, Jarek Blakarz wrote:
>
> 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.

--
Best regards,
Andrey Tarasevioch


All times are GMT. The time now is 05:27 AM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.