Using a function with variable argument strings

怎甘沉沦 提交于 2019-12-10 22:28:56

问题


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;
}

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?


回答1:


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).




回答2:


Variable arguments functions should not be used in C++.

The first argument is that they are only safe for PODs like int or char*, passing a non-POD C++ type has undefined behaviour.

Instead of creating a function with a long list of arguments, why don't you just create a vector and push back your strings into it?




回答3:


I am not sure but I would investigate the fact that va_* are macros, int a "primitive" type while string is not. Maybe this causes the problem somewhere.

EDIT: g++ gives an important warning: cannot receive objects of non-POD type ‘struct std::string’ through ‘...’; call will abort at runtime



来源:https://stackoverflow.com/questions/2983270/using-a-function-with-variable-argument-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!