Yet another way to shoot yourself in the foot with C++

Found during pair programming (yes, I do it sometimes):

class Foo {
public:
Foo(bool in);
...
};

...
Foo f = new Foo(true);
...

Yikes. Didn’t expect that to get by the compiler. But it did. Without even a warning. The compiler was happy to turn “new Foo” into a boolean value and instantiate f, silently letting the memory leak away.

This helps:

class Foo {
public:
explicit Foo(bool in);
...
};

But still. Ug. Single argument constructors in C++ are just evil.

This entry was posted in Software. Bookmark the permalink.