So I ran into a bug today where a NULL was passed into a constructor’s argument list and this caused the application to break. Its odd that the compiler did not prohibit this from happening. Since the argument list changed, the problem was not noticed until now. See the following code snippet:
This object takes 3 parameters, pay close attention to std::string&.
class Foo {
public:
std::string myName;
unsigned int someVariable;
void * ptr;
Foo(const std::string& name, void * aPtr, unsigned int variable);
~Foo();
}
Foo::Foo(const std::string& name, void * aPtr, unsigned int variable) : myName(name), ptr(aPtr), someVariable(variable)
{
// object constructed
}
int main(int argc, char* argv[])
{
// construct an instance of Foo
Foo foo(NULL /*whoops, passed in NULL when a string should be passed in*/,
"foo",
0); // program compiles as expected, A NULL pointer runtime error occurs when executed.
}
So basically, if you accidently switch your input values for your foo object the compiler does not do anything. No alarm is sounded and you are left scratching your head what happened when the program crashes. I would think there should be a way to prevent this from occurring. Is there something that works around this issue? Is there something in the compiler that should be turned on?
Actually, it’s not really
NULLthat is being passed by reference.std::stringhas a converting constructor that takes achar const*.NULLis a null pointer constant, so it can be used where achar const*is expected, so astd::stringobject is constructed from this null pointer. This construction yields undefined behavior.One option for providing a better warning to the user would be to add another constructor that has a
char const*parameter. This way you can easily add an assert in the constructor if null is passed in. It’s not a compile-time check, but it might be better than nothing if your run into this problem frequently (for what it’s worth, I can’t recall ever having run into this problem, so I’d argue that it’s not worth the effort).