[vlc-devel] commit: No need to create an object to handle the lock is such a simple case. ( R?mi Duraffort )

jpd at videolan.org jpd at videolan.org
Thu Jun 18 15:06:40 CEST 2009

On Thu, Jun 18, 2009 at 02:50:29PM +0200, R?mi Duraffort wrote:
> I thought that creating an object will add an overhead. As I'm not at
> all an expert of C++ I will trust you (and revert). Does it change
> something to the perf to have a virtual destructor ?

I haven't paid close attention, but using a constructor has about
the same cost as, sometimes a bit less than[1], calling an equivalent
new_MyObject() function. It gives you a bit of flexibility too since the
same constructor will be used regardless of how the object is created
(on the stack or on the heap using new).

Virtual destructors are pretty much required for any class that already
has virtual methods, and just like virtual methods they are called
through a pointer in a (hidden) table of virtual methods, the vtable.
Since that is the case it's usually by declaring the destructor virtual
that one forces a class to have a vtable.

If the type is unequivocally known then the compiler can optimize away
the virtual lookup for the call. Like when an object sits on the local

The final answer is (as usual) it depends. If the constructor or
destructor does a lot of work, you might not notice all the overhead
you're triggering by simply creating or destructing an object (and if
you're not careful, that might happen on each iteration in a loop, or
each call to an often-called function, for example).

But that shouldn't stop you from coming up with suitable constructors
and destructors for your classes, because if you can guarantee through
constructor and accessors that an existing object will have a certain
minimum state, then you can use that fact to eliminate a lot of error-
and state checking. That can make a lot of difference when calling the
class to do actual work.

And this concludes C++ constructors 101. :-)

[1] Perhaps due to inlining or use of member variable initializers.

More information about the vlc-devel mailing list