Thursday, June 14, 2007

store newed objects in smart pointers in standalone stmts

take an e.g.

int priority();
void processWidget( std::tr1::shared_ptr pw, int priority);

processWIdget( new widget() , priority() )
this wont compile because tr1 constructor in explicit

so how about


processwidget( std::Tr1:;shared_ptr( new widget) , priority());

this can cause a memory leak, say compiler decides to evaluate in this order:

new widget()
priority()
tr1::shared ptr ( widget)

if priority threw an exception then new widget wud be lost

the reason of this leak is that their is a lag between the time a resource is created and the time it is turned over to a resource managing object.
way out is simple:

std::tr1.sharedptr pw( new widget);
processwidget(pw , priority());

this works because compiler get less leeway in reordering operations across stmts that within them


things to remember:
store newed objects i nsmart pointers in standalone stmts. failure to do this can lead to subtle resource leaks when exceptions are thrown.

No comments: