Allow const mapped types in folly::AtomicHash(Array|Map)
authorBrett Simmers <bsimmers@fb.com>
Thu, 9 Jun 2016 00:19:20 +0000 (17:19 -0700)
committerFacebook Github Bot 7 <facebook-github-bot-7-bot@fb.com>
Thu, 9 Jun 2016 00:23:23 +0000 (17:23 -0700)
Summary:
Without this const_cast, it's impossible to insert anything into an
AHA with a const mapped_type, making it effectively useless.

Reviewed By: yfeldblum

Differential Revision: D3405687

fbshipit-source-id: 3ecba19e0e92661c2c537c747b4927176104939f

folly/AtomicHashArray-inl.h
folly/test/AtomicHashArrayTest.cpp

index 84b01ef307d7da8661e85a210c7da9f280249704..c6376822ab9fe904765477dba2684a32995c8bf6 100644 (file)
@@ -152,7 +152,11 @@ insertInternal(LookupKeyT key_in, ArgTs&&... vCtorArgs) {
               checkLegalKeyIfKey(key_new);
             }
             DCHECK(relaxedLoadKey(*cell) == kLockedKey_);
-            new (&cell->second) ValueT(std::forward<ArgTs>(vCtorArgs)...);
+            // A const mapped_type is only constant once constructed, so cast
+            // away any const for the placement new here.
+            using mapped = typename std::remove_const<mapped_type>::type;
+            new (const_cast<mapped*>(&cell->second))
+                ValueT(std::forward<ArgTs>(vCtorArgs)...);
             unlockCell(cell, key_new); // Sets the new key
           } catch (...) {
             // Transition back to empty key---requires handling
index 4facc7d797069b87c74042df8714df4e38840f01..92be30da9ae2fcfb9dfb17e53e308a644a2c348d 100644 (file)
@@ -333,3 +333,10 @@ TEST(Aha, LookupAny) {
     free(it.first);
   }
 }
+
+using AHAIntCInt = AtomicHashArray<int64_t, const int32_t>;
+
+TEST(Aha, ConstValue) {
+  auto aha = AHAIntCInt::create(10);
+  aha->emplace(1, 2);
+}