我有一些遺留時代的代碼在工作,它需要一個雙指針併爲其分配內存。它縮短的例子會是這個樣子:使用共享指針與在另一個函數中分配的內存
struct LegacyObj
{
int a;
double b;
};
void LegacyAllocator(LegacyObj** ppObj)
{
*ppObj = (LegacyObj*)malloc(sizeof(LegacyObj));
}
void LegacyDeleter(LegacyObj** ppObj)
{
free(*ppObj);
}
實際LegacyAllocator功能〜100線和混合讀取文件與創建LegacyObj指針鏈表,是不是我可以現在就重寫。然而,我想讓這個函數的使用更安全一點,避免因例外& tc引起的任何內存泄漏。我提出的第一個解決方案是把它包裝在一個類中,並處理調用ctor/dtor中的遺留函數。
class RAIIWrapper
{
public:
RAIIWrapper()
:obj{nullptr}
{
::LegacyAllocator(&obj);
}
RAIIWrapper(RAIIWrapper&& that)
: obj{ that.obj}
{
that.obj = nullptr;
}
RAIIWrapper& operator=(RAIIWrapper&& that)
{
RAIIWrapper copy{std::move(that)};
std::swap(obj, copy.obj);
return *this;
}
~RAIIWrapper()
{
::LegacyDeleter(&obj);
}
private:
LegacyObj* obj;
};
但我很好奇 - 是有辦法做到這一點使用std::shared_ptr
或std::unique_ptr
?我無法想出一個解決方案,而不必將原始指針保持傳遞給LegacyAllocator。
'unique_ptr'和'shared_ptr'不採取分配器,他們只需要刪除者。您將使用'LegacyAllocator(&obj)'自己分配指針,併爲調用'operator()' – David