Reputation: 26355
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 valid to pass in an int&
into a variable argument list? Or is it only safe to pass-by-value?
Upvotes: 1
Views: 473
Reputation: 64308
Section 5.2.2.7 of the C++03 standard says that lvalue-to-rvalue conversion is first performed, so your function should receive a copy of the int instead of a reference.
I tried it 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 an output of 7.
Upvotes: 2
Reputation: 929
No, it is not valid to pass in a reference because it is a non-POD type.
From the spec:
If the argument has a non-POD class type, the behavior is undefined.
See this related question on passing std::string, which is non-POD.
Code for reference: http://codepad.org/v7cVm4ZW
Upvotes: 0
Reputation: 1844
Yes, you can pass a reference to an int as here. You will be changing the global variable g_myInt if you changed that parameter in the function myVarArffunction...
Upvotes: -1