Thursday, December 15, 2011

Default constructors? Don't rely on it, there is no free lunch

C++ provides the following 4 functions if you don't provide one:

  • Constructor
  • Copy constructor
  • Destructor
  • Assignment operator
Most time, we think we can use these default constructors and no need to type our own. Since it is free, why not?

But sometimes, depending on the compiler, it may surprise you.  For example, for the following class:

struct Foo
{
    enum Enum
    {
       SIZE = 1024;
     }

 
     char m_buf[SIZE];
};


Is it any different from the following implementation?  Where we just provide a default constructor which does nothing.

struct Foo
{
    Foo()
    {}

    ~Foo()
     {}

    enum Enum
    {
       SIZE = 1024;
     }
 
     char m_buf[SIZE];
};

If you think they are same, you are wrong.  I am not sure whether it is a gcc bug or a C++ feature, but I tried both g++3.4.6 and g++ 4.1.2, the first implementation (without providing the constructor),  it is much much slower than the 2nd version.

If you just do a new, for the first implementation, it can take more than 100ns, and can grow to 300ns if the SIZE becomes 4096;
For the 2nd implementation,  it only take about 40ns, regardless of the size, e.g., either 2 bytes, or 4096 bytes.

From the assembler code, it looks the default constructor does some  memset, while the 2nd one does nothing,  really a surprise.

No comments:

Post a Comment