避免不正确的std :: string初始化与NULL const char *使用g ++

编程入门 行业动态 更新时间:2024-10-25 17:28:20
本文介绍了避免不正确的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 ++

本文发布于:2023-11-10 06:09:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1574564.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不正确   化与   std   char   string

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!