Skip to content

Instantly share code, notes, and snippets.

@milan11
Last active November 27, 2016 17:23
Show Gist options
  • Save milan11/5380035 to your computer and use it in GitHub Desktop.
Save milan11/5380035 to your computer and use it in GitHub Desktop.
not nullable boost shared_ptr
#pragma once
#include <boost/shared_ptr.hpp>
#define make_shared_ptr(T, ...) (boost::make_shared<T>(__VA_ARGS__))
#define make_shared_ref(T, ...) ((boost::shared_ref<T>)boost::make_shared<T>(__VA_ARGS__))
namespace boost {
template<class T>
class shared_ref {
public:
explicit shared_ref(const shared_ptr<T> & other_ptr) {
BOOST_ASSERT(other_ptr);
ptr = other_ptr;
}
#if defined(BOOST_HAS_RVALUE_REFS)
explicit shared_ref(shared_ptr<T> && other_ptr) {
BOOST_ASSERT(other_ptr);
ptr.swap(other_ptr);
}
#endif
shared_ref(const shared_ref<T> & other)
: ptr(other.ptr)
{
}
#if defined(BOOST_HAS_RVALUE_REFS)
shared_ref(shared_ref<T> && other) {
ptr.swap(other.ptr);
}
#endif
operator shared_ptr<T>() const {
return ptr;
}
T * operator->() const {
return ptr.get();
}
operator T&() const {
return *ptr;
}
bool operator==(const shared_ref<T> & other) const {
return ptr == other.ptr;
}
bool operator<(const shared_ref<T> & other) const {
return ptr < other.ptr;
}
void swap(shared_ref<T> & other) {
ptr.swap(other.ptr);
}
shared_ref<T> operator=(const shared_ref<T> & other) {
ptr = other.ptr;
return *this;
}
#if defined(BOOST_HAS_RVALUE_REFS)
shared_ref<T> operator=(shared_ref<T> && other) {
ptr.swap(other.ptr);
return *this;
}
#endif
private:
shared_ptr<T> ptr;
};
}
@firegurafiku
Copy link

#define make_shared_ptr(T, ...) (boost::make_shared<T>(__VA_ARGS__))
#define make_shared_ref(T, ...) ((boost::shared_ref<T>)boost::make_shared<T>(__VA_ARGS__))

Oh no, that's very, very broken. Why not to define your own make_ref function instead? (C++11 can do vararg templates!)

Copy link

ghost commented Nov 3, 2015

Hello,

good in "theory" ; really not acceptable in practice (as for Today) ; implementing your ref-counted-facet would require:

  • firstable, ensuring in a multi-threaded environnement the lifetime of refs ; ain't C++ work
  • secondable, if 1 were to be true ; you would have to implement the mechanism for any existing container.

not that your approach and idea are silly ; because these sort of discussions have been brought on the table during TR1 six years ago!

-- "Within C++ is a smaller, simpler, safer language struggling to get out." Bjarne
-- "Let's get it out but slowly else you would break any compatibility" Me-self

Best.

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