Setting std :: shared_ptr or boost :: shared_ptr to throw exceptions when NULL dereferencing

I have several projects that use boost::shared_ptreither std::shared_ptrextensively (I can quickly convert to any implementation if there is a good answer to this question for one, but not for the other). The Boost implementation uses Boost.Assert to avoid returning if a null pointer is found at operator*or operator->at runtime; while the libC ++ implementation does not seem to have any validation.

While, of course, the reality of a shared_ptrmust be verified before use, the large code base with a mixed paradigm makes me want to try a variation of the exception; since most of the code is relatively aware of exceptions and, for the most part, will not be in a high-level state, but in a renewable state, not std::terminate()segfault.

What is the best way to configure these accessors while maintaining reliability shared_ptr? It seems that the best option is encapsulation shared_ptrin throwing_shared_ptr, but I am afraid to break the magic. Is it best to copy the Boost source and just change ASSERTto the appropriate throwoperator?


The actual type name used everywhere for the corresponding type smart_ptr<T>is a typedef extended from a macro; i.e. it ForwardDeclarePtr(Class)expands to the following value:

class Class;
typedef boost::smart_ptr<Class> ClassPtr;

Everything passes, takes or stores ClassPtr- so I can quite easily replace the base type; and I suspect that this fixes a cut / hide issue.

+5
source share
2 answers

There std::shared_ptr<T>really is no “magic” that will be removed if you wrap it in a custom class that will throw an exception if it dereferences a NULLgeneric pointer. Therefore, I do not understand why this approach will not work if your new wrapper class follows all the semantics of the type std::shared_ptr<T>.

, , -, NULL std::shared_ptr<T> . , std::make_shared<T> . , , , , RAII, .

+5

std::shared_ptr throwing_shared_ptr, std::shared_ptr impl. , throwing_shared_ptr , , std::shared_ptr.

+5

All Articles