是否有任何 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/