【问题标题】:Turning this raw pointer situation into a unique_ptr?将这种原始指针情况转换为 unique_ptr?
【发布时间】:2015-06-12 21:23:31
【问题描述】:

我的代码如下所示:

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 有方法重置来改变它存储的指针,如果你需要的话。
  • 我的意思是,我可以在堆栈上分配一个空白的 unique_ptr,我的一个 if 填充它,然后如果它被一个 if 填充,则执行更新函数。
  • 是的,照字面意思做一样......?

标签: c++ c++11 smart-pointers unique-ptr


【解决方案1】:

你的代码就这么简单:

    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】:

    您可以使用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;
    

    【讨论】:

      【解决方案3】:

      unique_ptr&lt;&gt; 有一个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;
      

      【讨论】:

        猜你喜欢
        • 2017-07-05
        • 1970-01-01
        • 1970-01-01
        • 2021-03-18
        • 1970-01-01
        • 2019-06-22
        • 2022-07-07
        • 2016-06-02
        • 2014-01-01
        相关资源
        最近更新 更多