hjj*_*200 4 c++ variadic-functions
#include <cstdarg>
using namespace std;
void do_something( va_list numbers, int count ) {
// ^
// Should I call this by reference here? I mean, va_list & numbers?
//... stuff
va_end( numbers );
}
void setList( int count, ... ) {
va_list numbers;
va_start( numbers, count );
do_something( numbers, count );
}
int main() {
setList( 2, 0, 1 );
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当va_list进入另一个函数时,我应该如何将它传递给该函数?我知道va_end必须在完成任务时调用va_list我很困惑我是否应该通过引用来调用它.va_list即使没有通过引用调用,它也会正确结束吗?
小智 7
变量参数列表:
你永远不应该va_end在一个函数中使用va_listas参数!
从(Linux)手册页va_arg:
每次调用va_start()都必须与同一函数中相应的va_end()调用相匹配.
(强调我的)
在具有va_list参数的函数中,取va_listby值(作为C库函数,如vprintf...,do).
例:
#include <cstdarg>
#include <iostream>
void v_display_integers(int count, va_list ap) {
while(0 < count--) {
int i = va_arg(ap, int);
std::cout << i << '\n';
}
}
void display_integers(int count, ...) {
va_list ap;
va_start(ap, count);
v_display_integers(count, ap);
va_end(ap);
// You might use 'va_start' and 'va_end' a second time, here.
// See also 'va_copy'.
}
int main() {
display_integers(3, 0, 1, 2);
}
Run Code Online (Sandbox Code Playgroud)
注意:
在C++中,您应该避免使用变量参数列表.替代方案是std::array,std::vector,std::initializer_list和可变参数模板.