有没有办法禁止在c样式变量参数列表中使用类的值? [英] Is there a way to prohibit the use of a class by value in c style variable arguments list?

查看:103
本文介绍了有没有办法禁止在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; }

这里的printf调用通过值接收两个对象。这意味着他们的所有成员只是简单的内存复制。但是它们被解释为一个简单的char指针。结果是一个运行时错误当然。

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. :-(

请回答标题中的问题,我不需要讨论为什么不应该使用printf或这些变量参数列表 - 知道。

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.

感谢您的时间。

推荐答案

)检查 printf 参数是否匹配格式字符串中的格式说明符。

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

只要不要忘记添加 -Wformat -Wall 命令行选项。

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

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

这篇关于有没有办法禁止在c样式变量参数列表中使用类的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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