Will a boost smart pointer help me?
i am using Xerces to do some xml writing.
here's a couple of lines extracted from my code:
DOMLSSerializer *serializer = ((DOMImplementationLS*)implementation)->createLSSerializer();
serializer->release();
Is there a boost smart pointer that i can开发者_如何学Go use, so i can avoid calling serializer->release(); as it's not exception safe. The problem as i see it is that smart pointers can only call delete on your pointer object, could it be customised to call release?
thanks
Yes, smart pointers can call a custom "deleter" function object.
#include <iostream>
#include <tr1/memory>
struct Example {
void release() { std::cout << "Example::release() called\n"; }
};
struct ExampleDeleter {
void operator()(Example* e) { e->release(); }
};
int main()
{
{
std::tr1::shared_ptr<Example> p ( new Example, ExampleDeleter() );
}
std::cout << " see?\n";
}
(same for boost: see the shared_ptr(Y * p, D d); constructor.)
Yes, boost::shared_ptr
can be used with a custom deleter functor (as shown by Cubbi) or a deleter function:
void my_deleter(DOMLSSerializer* s) {
s->release();
}
// ...
boost::shared_ptr<DOMLSSerializer> serializer(foo->createLSSerializer(), my_deleter);
Don't know why people write their own wrapper that way any more @Cubbi
As answered to make shared ptr not use delete
shared_ptr<DOMLSSerializer> serializer(
((DOMImplementationLS*)implementation)->createLSSerializer(),
std::mem_fun(&DOMLSSerializer::release) );
If you just need a tiny RAII class then you could write the helper class yourself. It's so small that it barely pulls its own weight (let alone justifies pulling in a library):
class DOMLSSerializerOwner {
public:
DOMLSSSerializerOwner( DOMLSSerializer *serializer ) : m_serializer( serializer ) { }
~DOMLSSerializerOwner() { m_serializer->release(); }
operator DOMLSSerializer*() { return m_serializer; }
private:
DOMLSSerializerOwner( const DOMLSSerializerOwner &other ); // disabled
void operator=( const DOMLSSerializerOwner &rhs ); // disabled
DOMLSSerializer *m_serializer;
};
Then you can make your code read:
void f()
{
DOMLSSerializerOwner serializer = ((DOMImplementationLS*)implementation)->createLSSerializer();
serializer->doThis();
serializer->doThis();
// Look Ma: no release() call; 'serializer' does it automatically when going out of scope
}
精彩评论