Syntactic sugar
authorRajat Goel <rajatgoel2010@fb.com>
Mon, 17 Sep 2012 19:20:14 +0000 (12:20 -0700)
committerJordan DeLong <jdelong@fb.com>
Fri, 12 Oct 2012 04:32:55 +0000 (21:32 -0700)
Summary: This makes code easy to read for eyes used to unique/shared ptrs.

Test Plan: unit-tests

Reviewed By: delong.j@fb.com

FB internal diff: D575997

folly/ThreadLocal.h
folly/test/ThreadLocalTest.cpp

index a449ce67e62295aa6d95f386ee04be6ebe7c4232..55431645bfd3c6524ad084216aa8724480544f75 100644 (file)
@@ -79,7 +79,7 @@ class ThreadLocal {
 
   T* get() const {
     T* ptr = tlp_.get();
-    if (UNLIKELY(ptr == NULL)) {
+    if (UNLIKELY(ptr == nullptr)) {
       ptr = new T();
       tlp_.reset(ptr);
     }
@@ -94,7 +94,7 @@ class ThreadLocal {
     return *get();
   }
 
-  void reset(T* newPtr = NULL) {
+  void reset(T* newPtr = nullptr) {
     tlp_.reset(newPtr);
   }
 
@@ -168,7 +168,7 @@ class ThreadLocalPtr {
     return *get();
   }
 
-  void reset(T* newPtr) {
+  void reset(T* newPtr = nullptr) {
     threadlocal_detail::ElementWrapper& w =
       threadlocal_detail::StaticMeta<Tag>::get(id_);
     if (w.ptr != newPtr) {
@@ -177,6 +177,10 @@ class ThreadLocalPtr {
     }
   }
 
+  explicit operator bool() const {
+    return get() != nullptr;
+  }
+
   /**
    * reset() with a custom deleter:
    * deleter(T* ptr, TLPDestructionMode mode)
@@ -277,7 +281,7 @@ class ThreadLocalPtr {
         lock_(other.lock_),
         id_(other.id_) {
       other.id_ = 0;
-      other.lock_ = NULL;
+      other.lock_ = nullptr;
     }
 
     Accessor& operator=(Accessor&& other) FOLLY_NOEXCEPT {
@@ -288,7 +292,7 @@ class ThreadLocalPtr {
       // which is impossible, which leaves only one possible scenario --
       // *this is empty.  Assert it.
       assert(&meta_ == &other.meta_);
-      assert(lock_ == NULL);
+      assert(lock_ == nullptr);
       using std::swap;
       swap(lock_, other.lock_);
       swap(id_, other.id_);
@@ -296,7 +300,7 @@ class ThreadLocalPtr {
 
     Accessor()
       : meta_(threadlocal_detail::StaticMeta<Tag>::instance()),
-        lock_(NULL),
+        lock_(nullptr),
         id_(0) {
     }
 
@@ -312,7 +316,7 @@ class ThreadLocalPtr {
       if (lock_) {
         lock_->unlock();
         id_ = 0;
-        lock_ = NULL;
+        lock_ = nullptr;
       }
     }
   };
index d80b851eebd4e8c0cfe8d07c497c4b3f7aa12340..00f859439e35ad9966617437c44ac965421e7aed 100644 (file)
@@ -68,6 +68,16 @@ TEST(ThreadLocalPtr, CustomDeleter1) {
   EXPECT_EQ(10, Widget::totalVal_);
 }
 
+TEST(ThreadLocalPtr, resetNull) {
+  ThreadLocalPtr<int> tl;
+  EXPECT_FALSE(tl);
+  tl.reset(new int(4));
+  EXPECT_TRUE(static_cast<bool>(tl));
+  EXPECT_EQ(*tl.get(), 4);
+  tl.reset();
+  EXPECT_FALSE(tl);
+}
+
 // Test deleting the ThreadLocalPtr object
 TEST(ThreadLocalPtr, CustomDeleter2) {
   Widget::totalVal_ = 0;