使用带有可变参数字符串的函数 [英] Using a function with variable argument strings

查看:27
本文介绍了使用带有可变参数字符串的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在玩一些带有可变参数的函数,并决定制作一个函数来创建带有参数的向量.我创建 int 向量的函数有效...

I was playing around a bit with functions with variable arguments, and decided to make a function to create vectors with the arguments. My function for creating an int vector worked...

vector<int> makeIntVector(int numArgs, ...) {
    va_list listPointer;
    va_start(listPointer, numArgs);
    vector<int> made;
    for(int a = 0; a < numArgs; a++)
        made.push_back(va_arg(listPointer, int));
    va_end(listPointer);
    return made;
}

但不是我创建 string 向量的函数:

but not my function for creating a string vector:

vector<string> makeStringVector(int numArgs, string something, ...) {
    va_list listPointer;
    va_start(listPointer, something);
    vector<string> made;
    for(int a = 0; a < numArgs; a++)
        made.push_back(va_arg(listPointer, string));
    va_end(listPointer);
    return made;
}

导致程序崩溃.我做错了什么?

which crashes the program. What am I doing wrong?

推荐答案

尝试将字符串作为可变参数传递会导致未定义行为:如果参数具有非 POD 类类型(第 9 条),则行为未定义."(标准的§5.2.2/7).

Attempting to pass a string as a varaidic parameter gives undefined behavior: "If the argument has a non-POD class type (clause 9), the behavior is undefined." (§5.2.2/7 of the standard).

这篇关于使用带有可变参数字符串的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆