我有代碼看起來像這樣:把這個原始指針的情況變成一個unique_ptr?
ISessionUpdater* updater = nullptr;
if (eventName == "test")
updater = new TestJSONSessionUpdater(doc);
if (eventName == "plus")
updater = new PlusJSONSessionUpdater(doc);
if (updater)
{
bool result = updater->update(data);
delete updater;
return result;
}
return false;
有沒有辦法做這樣的事情,但與unique_ptr
?
也就是說,只有永遠具有1呼叫update(data)
而不是做:
if(cond)
make unique
call update
end
if(cond)
make unique
call update
end
...
unique_ptr有方法重置來更改它存儲的指針,如果這是你所需要的。 – Hcorg
我的意思是,我可以只在堆棧上分配一個空白的unique_ptr,其中一個ifs填充它,然後如果它由一個ifs填充,則執行update函數。 – jmasterx
是的,按照同樣的方式做它.........? –