• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
noatom

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

15 posts in this topic

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
0

Share this post


Link to post
Share on other sites

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
0

Share this post


Link to post
Share on other sites
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.
2

Share this post


Link to post
Share on other sites
Strictly, it's not legal C++ but from experience MSVC accepts it. gcc will not though, at least when set to be pedantic.
0

Share this post


Link to post
Share on other sites

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
0

Share this post


Link to post
Share on other sites
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
0

Share this post


Link to post
Share on other sites

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
0

Share this post


Link to post
Share on other sites

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?

0

Share this post


Link to post
Share on other sites

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.
1

Share this post


Link to post
Share on other sites

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).

0

Share this post


Link to post
Share on other sites

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

0

Share this post


Link to post
Share on other sites

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.

0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0