2015-06-12 68 views
4

我有代碼看起來像這樣:把這個原始指針的情況變成一個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 
... 
+1

unique_ptr有方法重置來更改它存儲的指針,如果這是你所需要的。 – Hcorg

+0

我的意思是,我可以只在堆棧上分配一個空白的unique_ptr,其中一個ifs填充它,然後如果它由一個ifs填充,則執行update函數。 – jmasterx

+1

是的,按照同樣的方式做它.........? –

回答

6

您的代碼將是如此簡單:

std::unique_ptr<ISessionUpdater> updater; 
    if (eventName == "test") 
     updater = std::make_unique<TestJSONSessionUpdater>(doc); 
    if (eventName == "plus") 
     updater = std::make_unique<PlusJSONSessionUpdater>(doc); 

    return updater ? updater->update(data) : false; 

您可以檢查std::unique_ptr幾乎相同的方式,你有原始指針

通知,要求部分是如何被簡化爲使用RAII的結果做。

2

​​具有operator bool轉換可用於查詢如果智能指針保持對象

std::unique_ptr<int> ptr; 
if (ptr) // Not yet assigned 
    std::cout << "This isn't printed"; 

因此您的密碼變爲

std::unique_ptr<ISessionUpdater> updater = nullptr; 
if (eventName == "test") 
    updater = std::make_unique<TestJSONSessionUpdater>(doc); 
if (eventName == "plus") 
    updater = std::make_unique<PlusJSONSessionUpdater>(doc); 

if (updater) // If this smart pointer owns an object, execute the block 
{ 
    bool result = updater->update(data); 
    return result; 
} 
return false; 
4

您可以使用std::make_unique來指定一個新的std::unique_ptr,並且它會銷燬舊的內部原始指針(如果它已經有一個)。

std::unique_ptr<ISessionUpdater> updater = nullptr; 
if (eventName == "test") 
    updater = std::make_unique<TestJSONSessionUpdater>(doc); 
if (eventName == "plus") 
    updater = std::make_unique<PlusJSONSessionUpdater>(doc); 

if (updater) 
{ 
    bool result = updater->update(data); 
    return result; 
} 
return false; 
相關問題