2012-12-02 77 views
2

GCC allows customization of printf specifiers.但是,我没有看到如何“教”它接受我的字符串类%s说明符。我的字符串类是一个简单的字符指针包装器,并且只有一个成员变量(char * data)并且没有虚函数。因此,将它按原样传递给printf-like函数代替常规的char *是可以的。问题是gcc静态分析器阻止我这样做,我必须明确地将它转换为const char *以避免警告或错误。GCC:为字符串输出定制printf

我的CString看起来是这样的:

class cstring 
{ 
    cstring() : data(NULL){} 
    cstring(const char * str) : data(strdup(str)){} 
    cstring(const cstring & str) : data(strdup(str.data)){} 
    ~cstring() 
    { 
     free(data); 
    } 
    ... 
    const char * c_str() const 
    { 
     return data; 
    } 

private: 
    char * data; 
}; 

示例代码,使用的CString:

cstring str("my string"); 
printf("str: '%s'", str); 

在GCC我得到这个错误:
错误:无法传递的对象非trivially- ''''类'cstring'到'
错误:格式'%s'需要类型'char *'的参数,但参数1具有类型'cstring'[-Werror = format]
cc1plus.exe:将所有警告视为错误

回答

1

C++标准不要求编译器支持此类代码,并且并非所有版本的gcc都支持它。 (https://gcc.gnu.org/onlinedocs/gcc/Conditionally-supported-behavior.html表明gcc-6.0至少 - 这个问题是否会与类似的类一起工作)。

C++ 11标准中的相关部分是5.2.2第7部分:

When there is no parameter for a given argument, the argument is passed in such a way that the receiving function can obtain the value of the argument by invoking va_arg ... Passing a potentially-evaluated argument of class type (Clause 9) having a non-trivial copy constructor, a non-trivial move constructor, or a non-trivial destructor, with no corresponding parameter, is conditionally-supported with implementation-defined semantics.

(但看看光明的一面:如果你进入使用c_str的习惯,那么至少你不会得到绊倒,当/如果你使用std::string。)