From d6995e311e68878df2ecd158ef2e057822e7a03a Mon Sep 17 00:00:00 2001 From: saurabh singh Date: Thu, 1 Oct 2015 01:06:13 +0530 Subject: [PATCH] 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. not_null(T t) : ptr_(move(t)) {...} 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. --- include/gsl.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/include/gsl.h b/include/gsl.h index 5ae4df6..7a66db2 100644 --- a/include/gsl.h +++ b/include/gsl.h @@ -111,7 +111,8 @@ class not_null { static_assert(std::is_assignable::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)) { ensure_invariant(); } not_null& operator=(const T& t) { ptr_ = t; ensure_invariant(); return *this; } not_null(const not_null &other) = default;