Using a function with variable argument strings

2019-07-21 16:36发布

问题:

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