避免不正确的std :: string初始化与NULL const char *使用g ++ [英] Avoiding improper std::string initialization with NULL const char* using g++

查看:245
本文介绍了避免不正确的std :: string初始化与NULL const char *使用g ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么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 ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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