Skip to content

Instantly share code, notes, and snippets.

@kkaefer
Last active August 29, 2015 14:06
Show Gist options
  • Save kkaefer/e5886b18095d7284c195 to your computer and use it in GitHub Desktop.
Save kkaefer/e5886b18095d7284c195 to your computer and use it in GitHub Desktop.
std::shared_ptr and std::unique_ptr that assert presence of member pointer on dereferencing
#pragma once
#include <memory>
#include <cassert>
namespace {
template <template <typename...> class H, typename ...A>
class asserting_ptr : public H<A...> {
public:
template <typename... Args>
inline asserting_ptr(Args &&... args)
: H<A...>(::std::forward<Args>(args)...) {}
inline auto operator->() const -> decltype(H<A...>::operator->()) {
assert(*this);
return H<A...>::operator->();
}
inline auto operator*() const -> decltype(H<A...>::operator*()) {
assert(*this);
return H<A...>::operator*();
}
};
}
namespace util {
template <typename... B> using ptr = asserting_ptr<::std::shared_ptr, B...>;
template <typename... B> using unique_ptr = asserting_ptr<::std::unique_ptr, B...>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment