c++ - Disallowing creation of the temporary objects -
while debugging crash in multithreaded application located problem in statement:
csinglelock(&m_criticalsection, true); notice creating unnamed object of csinglelock class , hence critical section object gets unlocked after statement. not coder wanted. error caused simple typing mistake. question is, there someway can prevent temporary object of class being created @ compile time i.e. above type of code should generate compiler error. in general, think whenever class tries sort of resource acquisition temporary object of class should not allowed. there way enforce it?
edit: j_random_hacker notes, possible force user declare named object in order take out lock.
however, if creation of temporaries somehow banned class, user make similar mistake:
// take out lock: if (m_multithreaded) { csinglelock c(&m_criticalsection, true); } // other stuff, assuming lock held ultimately, user has understand impact of line of code write. in case, have know they're creating object , have know how long lasts.
another mistake:
csinglelock *c = new csinglelock(&m_criticalsection, true); // other stuff, don't call delete on c... which lead ask "is there way can stop user of class allocating on heap"? answer same.
in c++0x there way this, using lambdas. define function:
template <class tlock, class tlockedoperation> void withlock(tlock *lock, const tlockedoperation &op) { csinglelock c(lock, true); op(); } that function captures correct usage of csinglelock. let users this:
withlock(&m_criticalsection, [&] { // stuff, lock held in context. }); this harder user screw up. syntax looks weird @ first, [&] followed code block means "define function takes no args, , if refer name , name of outside (e.g. local variable in containing function) let me access non-const reference, can modify it.)
Comments
Post a Comment