Pass Object by reference.

Hi,

If I have function prototype as
void function_test (AnyClass &obj);

and when i am calling this function

function_test(AnyClass());

I am getting error in XCode IDE(gcc compiler). and if I do the same thing in two step things are working fine.

1
2
AnyClass obj;
function_test(obj);


But I am not getting such error in visual studio.

Can anyone tell me how compiler handle these type of function call. And what I am doing wrong here?
closed account (1yR4jE8b)
Gcc is acting correctly, this is actually non-standard behaviour in Visual Studio's compiler. You are not allowed to pass temporary objects by non-const reference in standard C++.

1
2
3
4
void function_test(const AnyClass& obj){}

//then call it with
function_test(AnyClass()); //should work fine 
You should be getting the error.

Temporary objects can only be passed by const reference.

1
2
3
4
5
void func_const(const AnyClass& obj);  // take a const reference
void func(AnyClass& obj);  // take a non-const reference
//...
func_const( AnyClass() );  // OK - temporary is const
func( AnyClass() );  // ERROR - temporary is const, can't pass as nonconst 


There are reasons for this -- mainly to stop you from shooting yourself in the foot.

If the compiler allowed you to pass a temporary object by non-const reference, code like the below would silently screw you up:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Example
{
public:
  int v;

  Example(int V) : v(V) {}  // conversion ctor
};

void triple(Example& e)
{
  e.v *= 3;
}

int main()
{
  int v = 5;

  triple(v);  // expect it to triple 'v'

  cout << v;  // but it didn't!! wtf!
}


doing triple(v); creates a temporary Example and passes that to the function. Note that the temporary is modified, and not 'v'. But from the way main is written we would expect it to modify v.


But anyway yeah... it's a const correctness thing. Temporary objects can't be passed by non-const reference.


EDIT: doh, I was ninja'd
Last edited on
Thanks a lot for your's great and nice explanation... thanks
Topic archived. No new replies allowed.