Some days ago, I encountered a segmentation fault bug in a C++ program I am working on. Obviously, I expected gdb or valgrind would help me find the problem and make it go away… So I thought. All I found was: It’s a problem with the boost::shared_ptr destructor.
I started with a class like this:
class foo {
boost::shared_ptr foo_ptr;
int something;
int other_thing;
};
No problem – the objects were allocated, initialized, copied and deleted just like you would expect. However, when I added another member variable:
class foo {
boost::shared_ptr foo_ptr;
int something;
int other_thing;
int one_more_thing;
};
…I started to get segfaults in ~shared_ptr.
Immediately, I had the idea of writing a copy constructor for class foo. So I did. Same problem.
Only hours later, I found out that the compiler had apparently elided my copy constructor – it was never used! The compiler just chose to use the default copy constructor instead. When I moved the implementation of the copy constructor from the header to the .cpp, the compiler started using it, and all my problems went away.