Skip to main content
gamedev.net
🔒 Locked

Passing args by reference

Started by Amar0k Apr 8, 2005 at 6:22 PM 1 replies 700+ views
Original Post
Amar0k
Amar0k
Hi, I'm currently switching my project from VC6 to Dev-C++ and in the process finding stuff thats making me question my knowledge of C++. Passing args to functions by reference is one of those things thats giving me trouble. Consider the following:


#define UCHAR unsigned char

struct color_t
{
  color_t(UCHAR _r, UCHAR _g, UCHAR _b, UCHAR _a): r(_r), g(_g), b(_b), a(_a) {}

  UCHAR r, g, b, a;
};

void render_stuff( color_t &f) // <- notice the reference 
{
  // render stuff
}

int main()
{
  render_stuff( color_t(10, 10, 10, 255) );
  
  return 0;
}


It seems that VC6 is too forgiving on this one, since it lets me get away with this. Dev-C++ (MingW) on the other hand doesnt compile, telling me that 'no overloaded function blablabla...'. I always though of this as a 'unnamed' variable of type color_t being created on the stack (in main) and then passed by reference to render_stuff(), and it sort of made sense to me. I've based my Renderer class almost entirely in args passed by reference (vertices, normals, colors, etc...), but I still want the user to be able to call them 'on the fly' so to speak. Any way of getting around this or will I really have to switch to arguments passed by value? Thanks.
.Amar0k."In the beginning the Universe was created. This has made a lot of people very angry and been widely regarded as a bad move." -- Douglas Adams
Fruny
Fruny
You cannot pass unnamed temporaries by non-const reference.

Non-const reference implies you're going to modify the original variable, as a side-effect of your function. An unnamed temporary doesn't live beyond the statement it is created in. Modifying one such would be pointless and is therefore forbidden.

G++ 3.4.3 error message:

error: invalid initialization of non-const reference of type 'color_t&' from a temporary of type 'color_t'
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
Amar0k
Amar0k
Haha, thanks!

I'm glad I posted, I knew there would be a simple explanation.

Makes perfect sense, and of course my rendering functions should have had their arguments defined as const in the first place.

Thanks alot!
.Amar0k."In the beginning the Universe was created. This has made a lot of people very angry and been widely regarded as a bad move." -- Douglas Adams

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.