Unfortunately, C++ constructors challenged the second one:
class SampleBuffer { public: SampleBuffer(int alen) ; SampleBuffer(char const * astring) ; protected: std::unique_ptrEither you lived with two copies of the initialization code, or you created a private init() function which you called from both constructors. Not ideal, but I never worked in a group large enough that I had to worry about someone trying to call init() other than in the constructor. Still, it could happen, and that would probably be bad.m_buffer ; int m_len ; } ; SampleBuffer::SampleBuffer(int alen) : m_len(alen) { * m_buffer = new char[alen +1] ; } SampleBuffer::SampleBuffer(char const * astring) { int tmplen= strlen( astring) ; * m_buffer = new char[tmplen +1 ]; m_len= tmplen ; strncpy( * m_buffer, astring, tmplen) ; }
In C++11 they added constructor chaining which have shown up in other languages like c sharp and java. So now the constructors can look like this:
SampleBuffer::SampleBuffer(int alen) : m_len(alen) { * m_buffer = new char[alen +1] ; } SampleBuffer::SampleBuffer(char const * astring) : DRYBuffer(strlen(astring)) { strncpy( * m_buffer, astring, m_len) ; }Already an improvement, especially if you decide to change something like having m_len represent the size of the buffer including the null terminator (heaven help you tracking down that off by one error in the original with the two separate code paths).
Obviously this is just an example (only a small step above the other trivial examples out there), but I've done the init() thing before for non-trivial cases, and this will be a handy alternative.
Of course there's the issue of where you can use this, and where you can't. It looks like g++ 4.6 does not support this, but g++ 4.7 on works fine.
Labels: c++, c++11, programming
Feb '04
Oops I dropped by satellite.
New Jets create excitement in the air.
The audience is not listening.
Mar '04
Neat chemicals you don't want to mess with.
The Lack of Practise Effect
Apr '04
Scramjets take to the air
Doing dangerous things in the fire.
The Real Way to get a job
May '04
Checking out cool tools (with the kids)
A master geek (Ink Tank flashback)
How to play with your kids