更改 std::unique_ptr 中的指针而不销毁它

change pointer in std::unique_ptr without destroy it

我的 C++ 代码使用原始指针和 C 函数 mallocfreerealloc

我正在考虑将其更改为智能指针,但我真的想保留 realloc 功能,因为我认为它比 new 好得多,因为它不需要 "move"每次的内容。

如何使用 std::unique_ptr 重构它?

这是一些伪代码(我意识到这段代码不是 100% 安全的。事实上我从未尝试编译它)

class Demo{
   char *ptr;
   Demo(size_t size) : ptr( malloc(size) ){}

   bool resize(size_t size){
      char *ptr_new = realloc(ptr, size);

      if (ptr_new == nullptr){
         return false; // fail
      }

      // here is tricky part with std::unique_ptr,
      // ptr is already deleted...
      ptr = ptr_new;

      return true;
   }
};

重新分配指针而不删除它的方法是使用release():

auto old_ptr = unique.release();
unique.reset(new_ptr);

所以在你的代码中应该是这样的:

struct free_deleter {
    void operator(void* p) const { free(p); }
};

std::unique_ptr<char, free_deleter> ptr; // NB: malloc must be paired with free, not delete

bool resize(size_t size) {
    char* ptr_new = realloc(ptr.get(), size);
    if (!ptr_new) {
        return false;
    }

    ptr.release();
    ptr.reset(ptr_new); 
    return true;
}