Why can I call a nonconst function with a const object?

Started by
14 comments, last by Khatharr 11 years ago

Because temporaries returned from functions are r-values and considered const. You are not supposed/allowed to modify a temporary variable.

No, non-const temporaries are allowed to be modified, provided you go about it the right way. There are a few idioms that actually rely on it. Ex: the vector remove storage idiom

std::vector<Something>().swap(myVector); // clear and remove storage
std::vector<Something>(myVector).swap(myVector); // shrink capacity
When you get to C++11, you have rvalue references which are used to implement move semantics. Things like move constructors will also (usually) modify temporaries.
Advertisement

No, non-const temporaries are allowed to be modified, provided you go about it the right way. There are a few idioms that actually rely on it. Ex: the vector remove storage idiom


std::vector<Something>().swap(myVector); // clear and remove storage
std::vector<Something>(myVector).swap(myVector); // shrink capacity
When you get to C++11, you have rvalue references which are used to implement move semantics. Things like move constructors will also (usually) modify temporaries.

I knew somebody would point out that they aren't really const and even wondered if I should stick with "r-value" and drop the overly simple "const". But once you get into details about reference binding and how references must be const while calling non-const functions is perfectly fine, you start wondering "what the heck where they thinking?". While r-value references are a great tool, they are also great at completely confusing people and then you might have to get into even more detail to answer the inevitable question of "why not just allow non-const references?".

Side note: shrink_to_fit has finally put an end to the awkward swap-workaround (I can't myself to call it "idiom", simply because it kind of suggests that it was the intended method of doing it).

f@dzhttp://festini.device-zero.de

noatom, you seem reasonably bright. In the future could you please use thread titles that describe what the thread is about? If someone is wondering about this kind of issue in the future 'weird thing in c++' probably won't be in their search query.

smile.png

void hurrrrrrrr() {__asm sub [ebp+4],5;}

There are ten kinds of people in this world: those who understand binary and those who don't.

I edited the title

I edited the title

Yes, but now your title has nothing to do with the actual topic. Easily spotted by the fact that your code does not contain a single member function, const or otherwise. You are talking about passing temporaries as non-const references.

f@dzhttp://festini.device-zero.de

lol

Nevermind. Sorry.

void hurrrrrrrr() {__asm sub [ebp+4],5;}

There are ten kinds of people in this world: those who understand binary and those who don't.

This topic is closed to new replies.

Advertisement