not_null class makes an unnecessary copy,can't be used effectively with unique_ptr

Passing T by const ref instead of by value. This is important specially to prevent perf implications when this class is used for heavy to copy objects. A common example would  be shared_ptr. Another way to prevent two versions of the constructor is to have a single constructor and move the value. <code> not_null(T t) : ptr_(move(t)) {...} </code> This gives best of both worlds. For most cases I would have preferred this. But this can result in slightly bigger code since for the cases where this class is invoked from a copy of he object, the caller has to do the job of creating the copy.
This commit is contained in:
saurabh singh 2015-10-01 01:06:13 +05:30
parent fcff3fded1
commit d6995e311e

View File

@ -111,7 +111,8 @@ class not_null
{
static_assert(std::is_assignable<T&, std::nullptr_t>::value, "T cannot be assigned nullptr.");
public:
not_null(T t) : ptr_(t) { ensure_invariant(); }
not_null(const T &t) : ptr_(t) { ensure_invariant(); }
not_null(T &&t) : ptr_(std::forward<T>(t)) { ensure_invariant(); }
not_null& operator=(const T& t) { ptr_ = t; ensure_invariant(); return *this; }
not_null(const not_null &other) = default;