将引用类型传递到变量参数列表 [英] Passing reference types into variable argument list
本文介绍了将引用类型传递到变量参数列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
int g_myInt = 0;
int& getIntReference() { return g_myInt; }
void myVarArgFunction( int a, ... ) {
// .........
}
int main() {
myVarArgFunction( 0, getIntReference() );
return 0;
}
在上面的(未编译和未测试的)C ++代码中,在 int&
中变成可变参数列表?
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?
推荐答案
C ++ 03标准的第5.2.2.7节说,首先执行左值到右值转换,所以你的函数应该接收一个int的副本而不是引用。
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.
我使用g ++ 4.6尝试了这个程序。 3:
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;
}
输出为7。
这篇关于将引用类型传递到变量参数列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文