有什么g ++选项可以检测不正确的初始化std :: string与NULL const char *?
A there any g++ options which can detect improper initialization of std::string with NULL const char*?
我正在将一些int字段转换为std :: string,即:
I was in the process of turning some int fields into std::string ones, i.e:
struct Foo { int id; Foo() : id(0) {} };...变成:
struct Foo { std::string id; Foo() : id(0) {} //oooops! };我完全忽略了'id'初始化与0和g ++给我没有警告。这个错误在运行时检测到(std :: string构造函数抛出异常),但我真的想在编译时检测这样的东西。有什么办法吗?
I completely overlooked bad 'id' initialization with 0 and g++ gave me no warnings at all. This error was detected in the run time(std::string constructor threw an exception) but I'd really like to detect such stuff in the compile time. Is there any way?
推荐答案我认为它实际上是未定义的行为,
I think it is actually undefined behavior and not checked by the compiler. You are lucky that this implementation throws an exception.
但是,你可以通过以类型不可知的方式指定你想要的默认或零初始化来避免这样的问题: / p>
However, you can avoid such problems by specifying that you want default or zero-initialization in a type-agnostic way:
struct Foo { X id; Foo() : id() {} //note empty parenthesis };更多推荐
避免不正确的std :: string初始化与NULL const char *使用g ++
发布评论