其能够检测的std不当初始化::字符串NULL为const char * A有任何克++选择?

我是在转弯一些int字段成的std :: string的,即过程:

struct Foo
{
   int id;
   Foo() : id(0) {} 
};

...变成:

struct Foo
{
   std::string id;
   Foo() : id(0) {} //oooops!
};

我完全忽略坏的“身份证”初始化为0和g ++给了我没有警告的。在运行时检测到这个错误(的std :: string构造函数抛出异常),但我真的很喜欢在编译时检测到这样的东西。有什么办法?

有帮助吗?

解决方案

我认为它实际上是不确定的行为,而不是由编译器检查。你是幸运的,这个实现将引发异常。

但是,可以通过指定要默认或零初始化以类型不可知方式避免这样的问题

struct Foo
{
   X id;
   Foo() : id() {} //note empty parenthesis
};

其他提示

我不能想办法在编译时检测到这一点,所以我写了一个字符串生成器功能,与空指针正常交易:

//  FUNCTION :      safe_string(char const* pszS)
//  PARAMATERS :    pszS        source string to build a string from (may be NULL or 0-length)
//  DESCRIPTION :   Safely builds a string object from a char*, even a NULL pointer
//  RETURNS :       string

template<class C>
inline basic_string<C> safe_string(const C* input)
{
    if( !input )
        return basic_string<C>();
    return basic_string<C>(input);
}

我用这个每当我创建一个字符串,并有一个机会,输入可能是NULL。

有基础设施是在GCC来产生准确这种警告的:

void foo(const char* cstr) __attribute__((nonnull (1)));

void bar() {
    foo(0);
}

当与-Wnonnull(其由-Wall暗示)编译生产:

warning: null argument where non-null required (argument 1)

所以基本上你应该能够修改相关的系统头(或者,更好的实验,修改自己的$ HOME /位/ basic_string.h复制,然后覆盖系统中的一个与-isystem $HOME)类似的:

basic_string(const _CharT* __s, const _Alloc& __a = _Alloc())
    __attribute__((nonnull (1)));

然而这并没有帮助,因为(至少在4.0.1)-Wnonnull是不是在C ++支持和属性显然忽略。这不是显而易见的,为什么会这样;也许有人认为,它与过载或东西互动差些。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top