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

标签 c++ g++ stdstring

是否有任何 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 构造函数抛出异常),但我真的很想在编译时检测到这些东西。有什么办法吗?

最佳答案

我想不出一种在编译时检测到这一点的方法,所以我编写了一个字符串生成器函数来正确处理空指针:

//  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 时,我都会使用它。

关于c++ - 使用 g++ 使用 NULL const char* 避免不正确的 std::string 初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2407711/

相关文章:

json - std::string 到 rapidJson 对象的转换

c++ - 如何在 VSCode 中的 switch-case 语句中自动缩进?

c++ - 如何编写基于某些条件识别字符串中所选 float 或整数的C++正则表达式?

c++ - 关于g++中包含目录顺序的问题

c++ - 如何使用 glibc 的字符串实现在堆栈上分配 std::string?

c++ - 如何从作为模式给出的 std::string 中提取单词?

c++ - 使用 FFTW 并评估生成的傅里叶级数

C++ 使用 <algorithm> 对 vector 的 vector 进行划分

c++ - g++ 4.2 : internal compiler error: in make_thunk, 在 cp/method.c:129

C++ 11线程编译错误将字符串作为拷贝的引用传递