Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the copy constructor called when you dereferencing a pointer when passing by reference to a function [duplicate]

Tags:

c++

Possible Duplicate:
dereferencing a pointer when passing by reference

Is the copy constructor called when you dereferencing a pointer when passing by reference to a function?

Here is a simple example

int& returnSame( int &example ) { return example: }

int main()
{
  int inum = 3;
  int *pinum = & inum;

  std::cout << "pinum: " <<  returnSame(*pinum) << std::endl;

  return 0;          

}

My Guess what happeing:

When we dereference pinum we would expect the copy constructor to be called, but since the function is passed by value this will not be called?

If pinum copy constructor was called then a temporary object would be produced and the reference of that would be used, which would be very bad news in the form of undefined behaivour...

So what does happen...undefined behavior?

like image 239
MWright Avatar asked Jul 05 '12 15:07

MWright


1 Answers

No, the copy constructor is not called.

The dereference operator creates an lvalue referring to the existing object. The reference parameter is bound to this existing object.

like image 179
Ben Voigt Avatar answered Nov 14 '22 22:11

Ben Voigt