Skip to content

Instantly share code, notes, and snippets.

@ssylvan
Last active December 17, 2015 18:39
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ssylvan/5654932 to your computer and use it in GitHub Desktop.
Save ssylvan/5654932 to your computer and use it in GitHub Desktop.
Stupid C++ lib for trying to avoid null pointers
// Class for non-nullable pointers
template<class T>
class ptr
{
private:
T* m_ptr;
ptr(nullptr_t); // avoids init with nullptr
ptr(int); // avoids init with 0 or NULL
public:
explicit ptr(T* ptr) throw() : m_ptr(ptr) { assert(ptr != nullptr); };
ptr(const ptr<T>& other) throw() : m_ptr(other.m_ptr) {};
ptr& operator=(ptr other) throw()
{
m_ptr = other.m_ptr;
return *this;
}
T& operator*() const throw() { return *m_ptr; }
T* operator->() const throw() { return m_ptr; }
};
// Class for pointer that may be null. Can be converted to a 'ptr' using a dynamic
// check, but you can't do anything else with it.
template<class T>
class ptr_opt
{
private:
T* m_ptr;
public:
ptr_opt(T* ptr) throw() : m_ptr(ptr) {};
ptr_opt(const ptr_opt<T>& other) : m_ptr(other.m_ptr) {};
ptr_opt& operator=(ptr_opt other) throw()
{
m_ptr = other.m_ptr;
return *this;
}
// Just provides the "else_null" method, and either calls
// it or not, depending on the flag set.
class else_body
{
private:
const bool m_run_else_body;
else_body(bool run_else_body) throw() : m_run_else_body(run_else_body) {};
friend class ptr_opt<T>;
public:
template<class BODY>
void else_null(BODY body)
{
if (m_run_else_body) body();
}
};
/* Use like so:
myptr.not_null([&](ptr<T> p)
{
...
}).else_null([&]
{
...
});
Or just skip the else clause.
*/
template<class BODY>
else_body not_null(BODY body) const
{
if (m_ptr != nullptr)
{
body(ptr<T>(m_ptr));
return else_body(false);
}
else
{
return else_body(true);
}
}
};
@geekynils
Copy link

Interesting concept, but how will you wrap the allocation function to never return a null pointer. I mean what should happen if the OS is unable to allocate memory? I also wonder why the standard committee did not consider ths..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment