Customising std::shared_ptr or boost::shared_ptr to throw an exception on NULL dereference

こ雲淡風輕ζ 提交于 2019-12-05 06:59:00

There's really no "magic" in std::shared_ptr<T> that would be removed if you wrapped it inside a custom class that would throw an exception when dereferencing a NULL shared pointer. So I don't see why that approach wouldn't work, as long as your new wrapper-class follows all the semantics of the std::shared_ptr<T> type.

BTW, you could also take a slightly different approach, and that is create a wrapper-class that simply won't allow others to pass NULL pointers to the wrapped std::shared_ptr<T> data-member in the first-place. Basically it would be a class that would enforce the std::make_shared<T> idiom in its constructor. I'm not sure, based on the workings of your code if this is possible, but it's another way to circumvent the problem using a RAII approach rather than throwing exceptions.

Just subclass std::shared_ptr into throwing_shared_ptr, override those two methods, and have them assert and call through to std::shared_ptr's impl. This should work fine as long as you use throwing_shared_ptr everywhere instead of slicing it to a std::shared_ptr.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!