Jump to content

  • Log In with Google      Sign In   
  • Create Account

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


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
15 replies to this topic

#1 noatom   Members   -  Reputation: 782

Like
0Likes
Like

Posted 04 April 2013 - 07:43 AM

The code:

 

class ra{
public:

};


ra hey(){
ra io;
return io;
}

void e(ra& i){
	std::cout << "on" << std::endl;
}
int main() {
	e(hey());
}

 

 

Why does that compile? shouldn't the call to ra in main,return a temporary object,which is a const,an rvalue? So e shouldn't accept it,because it's a const!

 

Why does the above code work?


Edited by noatom, 08 April 2013 - 02:43 AM.


Sponsor:

#2 Juliean   GDNet+   -  Reputation: 2607

Like
0Likes
Like

Posted 04 April 2013 - 07:47 AM

Nothing that you don't explicitely declare as const is const. ra() will also construct a new "ra" class object on the stack, did you mean to call hey()? Would still work, though. You might even want to name test functions in a more clear manner, like "foo" for classes, somehow the "ra" naming confused me a bit.

 

Does this solve your question or is there anything else you'd like to know?

 

To show you the difference in code:

 

class foo {};

foo tempCopy()
{
return foo(); //returns a copy of the here created foo-object
}

const foo constCopy
{
return foo(); //returns a const copy of the here created foo
}

void testConstness(foo& object)
{
}

int main()
{
testConstness(tempCopy()); //compiles, but storage of reference/pointer will be invalid as soon as the main() function exits -> imagine this in other //function
testConstness(constCopy()); //won't compile

foo nonconst;
testConstness(nonconst); //compiles
const foo isconst;
testConstness(isconst); //won't compile
}

EDIT: Fixed the paranthesis...


Edited by The King2, 04 April 2013 - 10:50 AM.


#3 Cornstalks   Crossbones+   -  Reputation: 6990

Like
2Likes
Like

Posted 04 April 2013 - 07:57 AM

The code you posted doesn't work/compile. Why do you say it does? Are you using an old, crappy compiler with poor standards compliance?

Also, please include all #include directives to make it easier.

@The King2: his question is about binding a non constant reference to a temporary, which is a bit different from what you are showing/talking about.
[ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]

#4 BitMaster   Crossbones+   -  Reputation: 4088

Like
0Likes
Like

Posted 04 April 2013 - 07:58 AM

Strictly, it's not legal C++ but from experience MSVC accepts it. gcc will not though, at least when set to be pedantic.

#5 noatom   Members   -  Reputation: 782

Like
0Likes
Like

Posted 04 April 2013 - 08:27 AM

i'm using vs 2010 express,and i can run the code without any problem...

 

sorry,i wanted to call hey() as an argument,anyway,the code is the correct one now,still,it shouldn't work,but it does...


Edited by noatom, 04 April 2013 - 08:35 AM.


#6 Cornstalks   Crossbones+   -  Reputation: 6990

Like
0Likes
Like

Posted 04 April 2013 - 08:33 AM

Alright, now that I'm on a computer instead of a phone, I can properly respond to The King2's post...


// ...
int main()
{
    testConstness(tempCopy); //compiles, but storage of reference/pointer will be invalid as soon as the main() function exits -> imagine this in other //function


Nope, that won't compile. For two reasons. One, you're not calling the function, you're passing the address of the function. And two, even if you did call the function, it would be binding a non-const reference to a temporary, which is illegal.


    testConstness(constCopy); //won't compile


No, it won't, but that's because the constCopy function isn't declared right (it's missing parentheses at the end), and also because you're not calling it here (again, you're passing the address of the function). Then, of course, you have the whole "binding a non-const reference to a temporary" issue. But yes, you are right in that you can't use a non-const reference to refer to a const object.


    foo nonconst;
    testConstness(nonconst); //compiles
    const foo isconst;
    testConstness(isconst); //won't compile
}


These two are actually right.

Edited by Cornstalks, 04 April 2013 - 08:34 AM.

[ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]

#7 Cornstalks   Crossbones+   -  Reputation: 6990

Like
0Likes
Like

Posted 04 April 2013 - 08:41 AM

i'm using vs 2010 express,and i can run the code without any problem...

Ah, that's why. VS 2010 has a non-standard extension to allow this. If you bump up your warning level to level 4, you'll see:

 

warning C4239: nonstandard extension used : 'argument' : conversion from 'ra' to 'ra &'

          A non-const reference may only be bound to an lvalue
 
If you go into your project properties, then C/C++, then Language, you can see an option to "Disable Language Extensions" and if you disable them, your code will no longer compile.
 
GCC, VC++, and other compilers often include some "extensions" to the standard language.

Edited by Cornstalks, 04 April 2013 - 08:51 AM.

[ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]

#8 Juliean   GDNet+   -  Reputation: 2607

Like
0Likes
Like

Posted 04 April 2013 - 10:49 AM

Nope, that won't compile. For two reasons. One, you're not calling the function, you're passing the address of the function. And two, even if you did call the function, it would be binding a non-const reference to a temporary, which is illegal.

 

Ouch, I missed the () behind the functions, thats what you get from typing rushed out code from your mobile phone, yikes. But as somebody already pointed out, "two" is allowed in VS Studio. Is there some implication other than if we decided to store the reference why we should not do that?

 

sorry,i wanted to call hey() as an argument,anyway,the code is the correct one now,still,it shouldn't work,but it does...

 

It has already been elaborated why it works, at least for visual studio. Could you further explain why you, aside from that, think it should not work?



#9 Trienco   Crossbones+   -  Reputation: 2173

Like
3Likes
Like

Posted 04 April 2013 - 10:07 PM

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

 

You are also wrong about the lifetime. The lifetime of a temporary doesn't extend to the end of the surrounding block. It ends with the expression it is used in. One big and good to know exception is having a const reference to it, which will keep the temporary alive for as long as the reference exists.

 

doSomething(createTemporary());
//temporary dies here
 
{
     const Temp& temp = createTemporary();
     //do stuff
}
//temporary dies here, because reference goes out of scope

Edited by Trienco, 04 April 2013 - 10:07 PM.

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

#10 Cornstalks   Crossbones+   -  Reputation: 6990

Like
0Likes
Like

Posted 04 April 2013 - 10:47 PM

*snip*

+1, I'm going to leave this link here for the curious


[ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]

#11 SiCrane   Moderators   -  Reputation: 9597

Like
1Likes
Like

Posted 05 April 2013 - 08:02 AM

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.

#12 Trienco   Crossbones+   -  Reputation: 2173

Like
0Likes
Like

Posted 05 April 2013 - 11:49 PM

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

#13 Khatharr   Crossbones+   -  Reputation: 3002

Like
0Likes
Like

Posted 06 April 2013 - 09:56 PM

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.

#14 noatom   Members   -  Reputation: 782

Like
0Likes
Like

Posted 07 April 2013 - 08:45 AM

I edited the title



#15 Trienco   Crossbones+   -  Reputation: 2173

Like
0Likes
Like

Posted 07 April 2013 - 10:18 PM

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

#16 Khatharr   Crossbones+   -  Reputation: 3002

Like
0Likes
Like

Posted 07 April 2013 - 11:17 PM

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.




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS