diff --git a/src/common/ptr_util.h b/src/common/ptr_util.h index 481ccc7f393..feeba9d0bc7 100644 --- a/src/common/ptr_util.h +++ b/src/common/ptr_util.h @@ -29,6 +29,14 @@ struct ObserverOrUniquePtr : private D { explicit ObserverOrUniquePtr(T* ptr, ObserverOrUnique own) : ptr_(ptr), own_(own) {} ObserverOrUniquePtr(ObserverOrUniquePtr&& p) : ptr_(p.ptr_), own_(p.own_) { p.Release(); } + ObserverOrUniquePtr& operator=(ObserverOrUniquePtr&& p) { + Reset(p.ptr_); + own_ = p.own_; + p.Release(); + + return *this; + } + ObserverOrUniquePtr(const ObserverOrUniquePtr&) = delete; ObserverOrUniquePtr& operator=(const ObserverOrUniquePtr&) = delete; @@ -45,7 +53,15 @@ struct ObserverOrUniquePtr : private D { return ptr_; } + void Reset(T* ptr = nullptr) { + if (own_ == ObserverOrUnique::Unique) { + (*this)(ptr_); + } + + ptr_ = ptr; + } + private: T* ptr_; ObserverOrUnique own_; -}; \ No newline at end of file +}; diff --git a/src/storage/redis_db.cc b/src/storage/redis_db.cc index 4fbf006be5b..be3901a19ea 100644 --- a/src/storage/redis_db.cc +++ b/src/storage/redis_db.cc @@ -92,16 +92,15 @@ rocksdb::Status Database::Expire(const Slice &user_key, int timestamp) { } if (metadata.expire == timestamp) return rocksdb::Status::OK(); - char *buf = new char[value.size()]; - memcpy(buf, value.data(), value.size()); + auto buf = std::make_unique(value.size()); + memcpy(buf.get(), value.data(), value.size()); // +1 to skip the flags - EncodeFixed32(buf + 1, (uint32_t)timestamp); + EncodeFixed32(buf.get() + 1, (uint32_t)timestamp); auto batch = storage_->GetWriteBatchBase(); WriteBatchLogData log_data(kRedisNone, {std::to_string(kRedisCmdExpire)}); batch->PutLogData(log_data.Encode()); - batch->Put(metadata_cf_handle_, ns_key, Slice(buf, value.size())); + batch->Put(metadata_cf_handle_, ns_key, Slice(buf.get(), value.size())); s = storage_->Write(storage_->DefaultWriteOptions(), batch->GetWriteBatch()); - delete[] buf; return s; } diff --git a/tests/cppunit/ptr_util_test.cc b/tests/cppunit/ptr_util_test.cc index b685fe41523..22e306475a7 100644 --- a/tests/cppunit/ptr_util_test.cc +++ b/tests/cppunit/ptr_util_test.cc @@ -21,12 +21,13 @@ #include "common/ptr_util.h" #include -struct Counter { - Counter(int* i) : i_(i) { ++*i_; } +struct Counter { // NOLINT + explicit Counter(int* i) : i_(i) { ++*i_; } ~Counter() { --*i_; } int* i_; }; + TEST(ObserverOrUniquePtr, Unique) { int v = 0; { @@ -38,8 +39,14 @@ TEST(ObserverOrUniquePtr, Unique) { TEST(CompositePtr, Observer) { int v = 0; - ObserverOrUniquePtr observer(new Counter{&v}, ObserverOrUnique::Observer); + Counter* c = nullptr; + { + ObserverOrUniquePtr observer(new Counter{&v}, ObserverOrUnique::Observer); + ASSERT_EQ(v, 1); + + c = observer.Get(); + } ASSERT_EQ(v, 1); - delete observer.Release(); + delete c; ASSERT_EQ(v, 0); -} \ No newline at end of file +}