![]() |
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; } |
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 |
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 04:55 AM. |
Powered by vBulletin®. Copyright ©2000 - 2013, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.