Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to prohibit the use of a class by value in c style variable arguments list?

Tags:

c++

c

Accidential use of classes inside of c style typeless variable arguments list is a common error source. Example:

class MyString {
    public:
    char *pChars;
    int Length;

    MyString(char *pChars) {
        this->pChars = pChars; 
        Length = strlen(pChars); 
        } };

int main() {
    MyString s1("Bla1"), s2("Bla2");
    printf("%s%s", s1, s2); // This does not but should give a compiler warning/error!
    return 0; }

The printf call there receives the two s objects by value. that means all of their members are simply memory copied. But they are interpreted a simple char pointers. Result is a runtime error of course.

I am not asking for a solution to this, but I would like to have something I could add to my class so that the compiler warns me about it or gives an error.

Already tried to declarate but not implement a copy constructor. But it seems that no copy constructor is called. :-(

Please just answer to the question in the title. I do not need a discusson of why you should not use printf or these variable arguments lists - know that.

Thanks for your time.

like image 757
Ole Dittmann Avatar asked Aug 16 '10 13:08

Ole Dittmann


People also ask

What is a Variadic function in C?

Variadic functions are functions that can take a variable number of arguments. In C programming, a variadic function adds flexibility to the program. It takes one fixed argument and then any number of arguments can be passed.

Which type is used to store the arguments when the number of arguments for the function is not constant in C?

Variable length argument is a feature that allows a function to receive any number of arguments.

What is Va_list in C?

va_list is a complete object type suitable for holding the information needed by the macros va_start, va_copy, va_arg, and va_end. If a va_list instance is created, passed to another function, and used via va_arg in that function, then any subsequent use in the calling function should be preceded by a call to va_end.

How do you use variable arguments in C++?

Variable number of arguments in C++Define a function with its last parameter as ellipses and the one just before the ellipses is always an int which will represent the number of arguments. Create a va_list type variable in the function definition. This type is defined in stdarg. h header file.


1 Answers

Decent compilers (like gcc) check whether printf arguments match format specifiers in format string.

Just do not forget to add -Wformat or -Wall command line option.

http://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html

like image 52
qrdl Avatar answered Nov 14 '22 23:11

qrdl