Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding improper std::string initialization with NULL const char* using g++

Tags:

c++

g++

stdstring

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?

like image 288
pachanga Avatar asked Mar 09 '10 08:03

pachanga


2 Answers

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:

//  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);
}

I use this whenever I create a string and there's a chance the input might be NULL.

like image 153
John Dibling Avatar answered Oct 22 '22 04:10

John Dibling


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:

struct Foo
{
   X id;
   Foo() : id() {} //note empty parenthesis
};
like image 24
visitor Avatar answered Oct 22 '22 04:10

visitor