Passing reference types to a variable argument list

int g_myInt = 0;
int& getIntReference() { return g_myInt; }

void myVarArgFunction( int a, ... ) {
  // .........
}

int main() {
  myVarArgFunction( 0, getIntReference() );
  return 0;
}

In the (uncompiled and untested) C ++ code above, is it permissible to pass to a int&list of variables? Or is it safe to pass by value?

+1
source share
3 answers

Section 5.2.2.7 of the C ++ 03 standard states that lvalue-rvalue conversion is done first, so your function should get a copy of int instead of a link.

I tried this with this program using g ++ 4.6.3:

#include <iostream>
#include <stdarg.h>

int g_myInt = 7;
int& getIntReference() { return g_myInt; }

void myVarArgFunction( int a, ... )
{
  va_list ap;
  va_start(ap,a);
  int value = va_arg(ap,int);
  va_end(ap);
  std::cerr << value << "\n";
}

int main(int,char **)
{
  myVarArgFunction( 0, getIntReference() );
  return 0;
}

And got the result 7.

+2
source

No, it is not allowed to pass a link because it is a non-POD type.

From the specification:

If the argument has a class type other than POD, the behavior is undefined.

. std::string, POD.
: http://codepad.org/v7cVm4ZW

0

Yes, you can pass the link to int, as here. You will change the global variable g_myInt if you change this parameter in the myVarArffunction ...

-1
source

All Articles