使用 g++ 避免使用 NULL const char* 进行不正确的 std::string 初始化
是否有任何 g++ 选项可以检测带有 NULL const char* 的 std::string 的不正确初始化?
我正在将一些 int 字段转换为 std::string 字段,即:
struct Foo
{
int id;
Foo() : id(0) {}
};
...变成:
struct Foo
{
std::string id;
Foo() : id(0) {} //oooops!
};
我完全忽略了 0 的错误“id”初始化,而 g++ 根本没有给我任何警告。在运行时检测到此错误(std::string 构造函数引发异常),但我真的很想在编译时检测此类内容。有什么办法吗?
A there any g++ options which can detect improper initialization of std::string with NULL const char*?
I was in the process of turning some int fields into std::string ones, i.e:
struct Foo
{
int id;
Foo() : id(0) {}
};
...turned into:
struct Foo
{
std::string id;
Foo() : id(0) {} //oooops!
};
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
GCC 中有基础设施可以准确地产生此类警告:
当使用
-Wnonnull
(由-Wall
暗示)编译时,会产生:所以原则上你应该能够修改相关的系统标头(或者,更好地进行实验,修改您自己的 $HOME/bits/basic_string.h 副本,然后使用
-isystem $HOME
覆盖系统标头):没有帮助,因为(至少在 4.0.1 中)C++ 不支持
-Wnonnull
并且该属性显然被忽略。为什么会这样还不清楚;也许人们认为它与超载或其他什么相互作用很糟糕。There is infrastructure in GCC to produce exactly this sort of warning:
when compiled with
-Wnonnull
(which is implied by-Wall
) produces:So in principle you ought to be able to modify the relevant system header (or, better for experimenting, modify your own $HOME/bits/basic_string.h copy and then override the system one with
-isystem $HOME
) similarly:However this doesn't help because (at least in 4.0.1)
-Wnonnull
is not supported in C++ and the attribute is apparently ignored. It's not obvious why this is so; perhaps it was felt that it interacted badly with overloading or something.我想不出一种方法可以在编译时检测到这一点,所以我编写了一个字符串生成器函数来正确处理空指针:
每当我创建字符串时我都会使用它,并且输入有可能为 NULL。
I can't think of a way to detect this at compile-time, so I wrote a string builder function that properly deals with null pointers:
I use this whenever I create a string and there's a chance the input might be NULL.
我认为这实际上是未定义的行为,并且没有由编译器检查。你很幸运,这个实现抛出了异常。
但是,您可以通过以类型无关的方式指定您想要默认或零初始化来避免此类问题:
I think it is actually undefined behavior and not checked by the compiler. You are lucky that this implementation throws an exception.
However, you can avoid such problems by specifying that you want default or zero-initialization in a type-agnostic way: